我有一个看起来像的测试课
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-context.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
public abstract class TestClass {
@Rule @Resource public JUnitRuleMockery jMockContext;
public void test1() {
//Expectations and test
}
public void test2() {
//Expectations and test
}
}
在test-context.xml
我通过定义了JUnitRuleMockery
plus几个模拟对象factory-method
,例如
<bean id="mockContextFactory" class="MockContextFactory" />
<bean id="jMockContext" factory-bean="mockContextFactory" factory-method="getContext" scope="prototype" />
<bean id="firstMock" factory-bean="mockContextFactory" factory-method="getFirstMock" />
<bean id="secondMock" factory-bean="mockContextFactory" factory-method="getSecondMock" />
MockContextFactory
是
public class MockContextFactory
{
private JUnitRuleMockery jUnitRuleMockery;
public MockContextFactory() {
jUnitRuleMockery = new JUnitRuleMockery();
jUnitRuleMockery.setThreadingPolicy(new Synchroniser());
}
public JUnitRuleMockery getContext() {
return jUnitRuleMockery;
}
public FirstMock getFirstMock() {
return jUnitRuleMockery.mock(FirstMock.class);
}
//others getter
}
在TestClass
我有几种测试方法中,由于有注释@DirtiesContext
,我希望在每次测试执行后重新加载Spring上下文(由于每个测试都对模拟对象设置了期望,因此每次都必须重新加载Spring上下文)。从这里看到@DirtiesContext。但是,似乎没有重新加载Spring上下文:实际上,在test2
(可能test1
早些时候已执行)的开始处以调试模式进入时,我jMockContext
仍然可以看到期望,执行列表和错误(如果有)test1
。
所以,最后有几个问题,@DirtiesContext
真的导致Spring上下文被重新加载(据我从Spring Docs了解),还是我误解了注释?在第一种情况下,我在做什么错?在后一种情况下,如何强制为每个测试重新加载Spring上下文?
编辑,以界定问题:我的代码像上面的示例一样从几天开始运行,然后今天我创建了一个新测试,在其中添加了失败的期望。然后,我看到该类中的所有其他测试由于相同的原因而失败(green
直到今天为止)。调试时,我发现它jMockContext
从未清除,这意味着所有测试都将期望添加到同一池中:当然,只要没有期望失败,那是透明的,而且我没有注意到(test1
添加并传递很少的期望,test2
需要一个非空的期望池已经通过并添加了自己的期望值,因此没有问题),但是我不喜欢以前的情况,并且我想在没有预先设定的期望的情况下开始每个测试。
这是我的解决方案。我不知道这是否仅限于Spring 3.2还是一个普遍的误解,但是仅仅使用@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
它不足以使整个Spring上下文为每个测试重新加载。我还必须添加DirtiesContextTestExecutionListener
in @TestExecutionListeners
。
因此,最后,对我有用的只是将我的注释更改TestClass
为
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-context.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@TestExecutionListeners({DirtiesContextTestExecutionListener.class})
public abstract class TestClass
没什么要改变的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句