如http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management-caching中所述,Spring将始终尝试根据生成的密钥缓存测试上下文。
但是,有没有办法缓存失败加载的测试环境?换句话说 - 如果测试上下文失败加载,我不想要进一步测试重新尝试加载它。实际上,它们应该立即失败并导致初始上下文加载尝试失败的相同错误。
那么,有没有办法在Spring中做到这一点?例如,如果我尝试加载其生成密钥的上下文"与之前的加载失败相同,只是失败立即与初始上下文加载尝试失败的同一错误/.
答案 0 :(得分:1)
不,从Spring Framework 4.0.5开始,没有用于缓存失败 ApplicationContext
的机制。
如果这是您希望在Spring TestContext Framework中引入的功能,请create a JIRA issue获取“Spring Framework”项目和“Test”组件。
此致
Sam(Spring TestContext Framework的作者)
答案 1 :(得分:0)
对此的一种解决方案是创建您自己的ContextLoader并重写loadContext方法。例如,对于使用WebAppConfiguration的测试,您可以使用类似
的内容覆盖WebDelegatingSmartContextLoaderpublic 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)