给定一个使用 spring 的测试实用程序注释 ContextConfiguration 来创建 bean 的 testng 类,这些 bean 在测试类的生命周期内只创建一次。
在使用它之前,我总是使用@BeforeMethod 在每个@Test 方法之前重建所有内容。
我的问题:有没有办法让 spring 为每个 @Test 方法重建 bean?
//The beans are unfortunately created only once for the life of the class.
@ContextConfiguration( locations = { "/path/to/my/test/beans.xml"})
public class Foo {
@BeforeMethod
public void setUp() throws Exception {
//I am run for every test in the class
}
@AfterMethod
public void tearDown() throws Exception {
//I am run for every test in the class
}
@Test
public void testNiceTest1() throws Exception { }
@Test
public void testNiceTest2() throws Exception { }
}
最佳答案
如果您希望在每次测试运行时重新加载上下文,那么除了@ContextConfiguration 之外,您还应该扩展 AbstractTestNGSpringContextTests 并使用@DiritesContext 注释。一个例子:
@ContextConfiguration(locations = {
"classpath:yourconfig.xml"
})
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class YourTestClass extends AbstractTestNGSpringContextTests {
//magic
}
Context.ClassMode.AFTER_EACH_TEST_METHOD 的类模式将导致 spring 在调用每个测试方法后重新加载上下文。您还可以使用 DirtiesContext.ClassMode.AFTER_CLASS 在每个测试类之前重新加载上下文(对于在所有启用 spring 的测试类的父类(super class)上使用很有用)。
关于java - testng 类中的 Spring @ContextConfiguration 测试配置每个测试类只创建一次 beans,而不是每个测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10730576/