正如http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management-caching提到的,Spring将总是试图根据一些生成的密钥缓存测试环境。
但是,是否有缓存加载失败的测试情境的方法吗?换句话说 - 如果一个测试情境加载失败,我不希望进一步测试,以重新尝试加载它。事实上,他们应该立即引起初始上下文装载尝试失败同样的错误失败。
那么,有没有办法在Spring做到这一点?例如,如果我尝试加载其“生成的密钥”上下文是一样一前一加载失败,只是同样的错误,最初的情况下装载尝试失败/立即失败。
不,Spring框架4.0.5有用于缓存失败的ApplicationContext
的机制。
如果这是你想在Spring TestContext框架看到引入的功能,请create a JIRA issue为“Spring框架”项目和“测试”的组成部分。
问候,
山姆(Spring的TestContext框架的作者)
一种解决方法是创建你自己的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)