【问题标题】:Cache context in Spring test even if it failed to load即使加载失败,也要在 Spring 测试中缓存上下文
【发布时间】:2014-05-20 09:40:26
【问题描述】:
【问题讨论】:
标签:
java
spring
testing
junit
spring-test
【解决方案1】:
不,从 Spring Framework 4.0.5 开始,没有缓存 失败 ApplicationContext 的机制。
如果这是您希望在 Spring TestContext Framework 中引入的功能,请create a JIRA issue 获取“Spring Framework”项目和“Test”组件。
问候,
Sam(Spring TestContext 框架的作者)
【解决方案2】:
对此的一种解决方案是创建您自己的 ContextLoader 并覆盖 loadContext 方法。例如,对于使用 WebAppConfiguration 的测试,您可以使用类似于
的内容覆盖 WebDelegatingSmartContextLoader
public class FastFailContextLoader extends WebDelegatingSmartContextLoader {
private static boolean initialized = false;
@Override
public ApplicationContext loadContext(MergedContextConfiguration mergedConfig) throws Exception {
if (initialized) {
throw new IllegalArgumentException(
"The ApplicationContext has already attempted to initialize. Aborting subsequent initialization. Check "
+ "earlier logs for original error");
}
setInitialized();
return super.loadContext(mergedConfig);
}
private static void setInitialized() {
initialized = true;
}
}
然后你只需要注释你的测试
@ContextConfiguration(loader = FastFailContextLoader.class)