【问题标题】:Cache context in Spring test even if it failed to load即使加载失败,也要在 Spring 测试中缓存上下文
【发布时间】:2014-05-20 09:40:26
【问题描述】:

正如http://docs.spring.io/spring/docs/current/spring-framework-reference/html/testing.html#testcontext-ctx-management-caching 中提到的,Spring 总是会尝试根据一些生成的键来缓存测试上下文。

但是,有没有办法缓存未能加载的测试上下文?换句话说——如果一个测试上下文加载失败,我确实想要进一步的测试来重新尝试加载它。事实上,它们应该立即失败,并出现导致初始上下文加载尝试失败的相同错误。

那么,有没有办法在 Spring 中做到这一点?例如,如果我尝试加载一个“生成的密钥”与之前加载失败的上下文相同的上下文,则立即失败,并出现与初始上下文加载尝试失败相同的错误/。

【问题讨论】:

    标签: 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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-11
        • 1970-01-01
        • 2017-10-31
        • 1970-01-01
        • 2014-12-19
        • 2016-06-23
        • 2020-08-28
        • 1970-01-01
        相关资源
        最近更新 更多