![](/img/trans.png)
[英]TestNg's @BeforeTest on base class only happening once per fixture
[英]Spring's @ContextConfiguration test configuration in a testng class is creating beans only once per test class, not per test
给定一个使用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的测试类,可用于超类)。
你的旧@BeforeMethod可能是正确的方法。
@ContextConfiguration旨在在类级别注入bean - 换句话说,它的工作方式完全符合设计。
另一种可能性是使用原型范围的bean。 每次实例化测试类时,都会实例化原型范围bean并将其连接起来。
请注意,JUnit和TestNG使用不同的逻辑来确定何时实例化测试类。 JUnit为每个方法创建一个新实例,TestNG重用测试实例。 鉴于问题是关于TestNG,您需要将测试分解为许多测试类以实现整体效果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.