如何测试“脏”的Spring应用程序上下文?

4

Spring框架文档中指出:

在极少数情况下,测试可能会“污染”应用程序上下文,需要重新加载 - 例如,通过更改bean定义或应用程序对象的状态 - Spring的测试支持提供了机制,在执行下一个测试之前重新加载配置并重建应用程序上下文。

有人能详细解释一下吗?我不太明白。最好有例子。

1个回答

8
每个JUnit测试方法都假定是隔离的,也就是说没有任何副作用可能会导致另一个测试方法的行为不同。这可以通过修改由Spring管理的bean的状态来实现。
例如,假设您有一个由Spring管理的类为MySpringBean的bean,它具有一个字符串属性,其值为"string"。以下测试方法testBeanString将根据它是在testModify方法之前还是之后调用而产生不同的结果。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/base-context.xml"})
public class SpringTests {

    @Autowired
    private MySpringBean bean;

    @Test public void testModify() {
        // dirties the state of a managed bean
        bean.setString("newSring");
    }

    @Test public void testBeanString() {
        assertEquals("string", bean.getString());
    }
}

使用@DirtiesContext注解表示测试方法可能会改变Spring管理的Bean的状态。

1
你好,你知道是否有办法手动调用脏上下文吗?不幸的是,我不能使用注释或扩展类。 - AlanFoster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接