当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How can performed method setUp only once in tests

问题描述:

I have test:

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = {TestRepositoryConfig.class})

@Transactional

public class ServiceTest {

@Autowired

private UserRepository userRepository;

@Autowired

private Service service;

static {

initTestUser();

}

public void setUp() {

userRepository.seve(testUser);

}

public void test1() { ... }

public void test2() { ... }

I need first start method setUp, saving testUser, then start methods test1 and test2. Method setUp must performed only once! How can do it?

网友答案:

I believe the problem you are trying to solve should be done in a different way. As far as I see you want to fill your DB with some test data, and this is better to do in a global configuration for all tests.

But if you want to stick to your initial idea you can try an approach with listeners described in this blog post.

网友答案:

Use the @BeforeClass annotation

public class MyTest {
     @BeforeClass public static void setupClass() { /* Set up stuff once */ }
     @Test public void test1() { /* ... */ }

}

Note however that the static method does not have access to instance members, and the things you want to set up before the tests run need to be static. It's advisable to clean up afterwards with @AfterClass

分享给朋友:
您可能感兴趣的文章:
随机阅读: