【问题标题】:How can a test 'dirty' a spring application context?测试如何“弄脏”弹簧应用程序上下文?
【发布时间】:2010-07-22 06:55:10
【问题描述】:

spring framework documentation 声明:

在不太可能的情况下,测试可能 “脏”应用程序上下文, 需要重新加载 - 例如,通过 更改 bean 定义或 应用程序对象的状态 - Spring 的测试支持提供 导致测试夹具的机制 重新加载配置和 之前重建应用程序上下文 执行下一个测试。

有人可以详细说明吗?我只是不明白。例子会很好。

【问题讨论】:

    标签: spring testing junit


    【解决方案1】:

    假设每个 JUnit 测试方法都是隔离的,即没有任何可能导致另一个测试方法表现不同的副作用。这可以通过修改spring管理的bean的状态来实现。

    例如,假设您有一个由 MySpringBean 类的 spring 管理的 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的状态。

    【讨论】:

    • 谢谢,我想我现在明白了。
    • 嗨,你知道有没有办法手动调用脏上下文?不幸的是,我不能使用注释或扩展类..
    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2019-09-14
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-22
    • 2014-11-02
    相关资源
    最近更新 更多