【问题标题】:Automatically terminate all integration tests if `Failed to load ApplicationContext` error occurs如果发生 `Failed to load ApplicationContext` 错误,自动终止所有集成测试
【发布时间】:2021-12-13 14:31:51
【问题描述】:

我们有一些集成测试(使用 spring 框架编写)由于 bean 初始化异常而失败,最终导致 Failed to load ApplicationContext 。根据我对 spring testing docs 的理解,ApplicationContext 的加载发生在类级别,所以我的疑问是 -

  1. 一旦在集成测试类运行期间ApplicationContextbean 初始化异常 而失败(即Failed to load ApplicationContext),ApplicationContext 是否会尝试再次启动(最终将失败)该特定集成测试类中存在的每个单独的集成测试?

    1. 询问上述情况是因为当 bean 发生故障时,我们看到与 postgres 的连接数量激增,似乎对于集成测试类中存在的每个集成测试(最终由于 Failed to load ApplicationContext 而失败),spring 试图创建一个到 postgres 的新连接,并且在 ApplicationContext 失败之前不会破坏它。我们如何才能阻止这种情况,请提供一些建议。
  2. 另外,一旦我们得到Failed to load ApplicationContext,有没有办法以编程方式完全自动终止所有集成测试的运行?如果是,请帮助如何实现它? 谢谢。

测试框架 - junit + Spring

更新:使用了提到的测试框架。

【问题讨论】:

    标签: java spring spring-boot integration-testing spring-test


    【解决方案1】:

    如果ApplicationContext 反复加载失败,目前无法中止集成测试。

    要投票支持此类支持,请参阅this Spring Framework issue

    【讨论】:

      【解决方案2】:

      如果您使用的是 JUnit,请在您的测试类中添加以下登录名。

      public class BaseClass {
      
      @BeforeClass
          public void isApplicationContextFailed() {
              //logic to check for application failure
          }
      
      
      //continue with your test methods.
      }
      

      建议您通过以下参考资料了解详细信息。

      https://junit.org/junit4/javadoc/4.13/org/junit/BeforeClass.html

      https://howtodoinjava.com/testng/testng-before-and-after-annotations/

      【讨论】:

        【解决方案3】:
        1. 如果您在测试类中有多个集成测试,那么它将失败多次。

        2. 您可以使用 dependsOnGroups 属性终止所有集成测试用例。

        例如,您可以有一个方法来检查是否存在 bean 异常失败,并将所有其他测试声明为依赖于该方法。但这可以使用 TestNG 完成

        @Test(groups = { "isApplicationContextFailed" }) // you can run with simply @Test here if there is only one independent test.
        public void isApplicationContextFailed() {}
        
        @Test(dependsOnMethods = { "isApplicationContextFailed" })
        public void queryTestOne() {}
        
        @Test(dependsOnMethods = { "isApplicationContextFailed" })
        public void queryTestTwo() {}
        

        您可以从 TestNG 中探索更多信息 -> https://testng.org/doc/documentation-main.html#dependent-methods

        注意:- 如果您使用的是 JUnit,还有其他一些方法可以做到这一点。在这种情况下请更新。

        【讨论】:

        • 嗨 Narasimha,我已经更新了问题,提到了 junit + spring 作为测试框架。请建议。谢谢。
        • 然后你可以简单地在一个依赖方法中使用@BeforeClass注解,它会首先检查应用上下文失败。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-01
        • 2022-12-07
        • 2021-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多