java - testng 类中的 Spring @ContextConfiguration 测试配置每个测试类只创建一次 beans,而不是每个测试

标签 java spring unit-testing testng

给定一个使用 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/

相关文章:

java - 在 Java 中移动 JLabel

java - MySQLIntegrityConstraintViolationException : Duplicate entry '1' for key 'PRIMARY'

java - 如何对基于 HashMap 值生成字符串的函数进行单元测试?

php - SimpleTest:如何断言抛出 PHP 错误?

java - Android 应用程序 Iframe 网站

java - 当表单验证失败时,Struts Controller 将重定向到哪里?

Spring LDAP Context.REFERRAL 遵循

java - Spring 网络流量 : redirect http to https

python - 如何为 Flask 后单元测试 Python 复制 Multidict

java - Tomcat 是否实现或运行 Java Servlet 和 JavaServer Pages (JSP) 规范?