【发布时间】:2016-09-01 16:55:32
【问题描述】:
我的 Spring 集成测试中有一个特定的类(比如说MyTest),它在 Spring 组件上使用 PowerMock @PrepareForTest 注释:@PrepareForTest(MyComponent.class)。这意味着 PowerMock 将加载这个类并进行一些修改。问题是,我的@ContextConfiguration 定义在由MyTest 扩展的超类上,而ApplicationContext 缓存在不同的测试类之间。现在,如果首先运行MyTest,它将具有MyComponent 的正确PowerMock 版本,但如果不是,则测试将失败,因为将为另一个测试加载上下文(没有@PrepareForTest)。
所以我想做的是在MyTest 之前重新加载我的上下文。我可以通过
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
但是如果我还想在测试完成后重新加载上下文怎么办?所以我将再次拥有干净的MyComponent,而无需修改 PowerMock。有没有办法同时做到BEFORE_CLASS 和AFTER_CLASS?
现在我用以下 hack 做到了:
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
在 MyTest 上,然后
/**
* Stub test to reload ApplicationContext before execution of real test methods of this class.
*/
@DirtiesContext(methodMode = DirtiesContext.MethodMode.BEFORE_METHOD)
@Test
public void aa() {
}
/**
* Stub test to reload ApplicationContext after execution of real test methods of this class.
*/
@DirtiesContext(methodMode = DirtiesContext.MethodMode.AFTER_METHOD)
@Test
public void zz() {
}
我想知道是否有更漂亮的方法可以做到这一点?
作为一个附带问题,是否可以只重新加载某些 bean 而不是完整的上下文?
【问题讨论】:
-
为什么要在测试之前将上下文标记为脏?
-
如前所述,我想为 MyTest 类重新加载上下文,所以我的 @PrepareForTest(MyComponent.class) 将起作用。
标签: java spring spring-test