需要能够在单元测试中捕获 Spring 启动异常

Need to be able to catch Spring startup exception in unit test

我有这样一种情况,我们想在启动时检查 Spring MVC 代码,并在不满足某些条件时抛出异常(从而导致 ApplicationContext 失败)。

有没有办法检测 JUnit 测试以捕获 Spring 启动(具体来说,在大多数情况下是 Spring 启动)异常,这样它们就不会导致测试失败?如果异常没有发生,我基本上想通过测试。

我昨天解决了这个问题。因为默认的 SmartContextLoader 类 像 AnnotationConfigWebContextLoaderSpringApplicationContextLoader,它们被注释引入,完全加载了 ApplicationContext,我在那里无法捕捉到任何异常.

我想出的解决方案——我相信还有更优雅的解决方案——是创建我自己的 SmartContextLoader 实现,将所有内容委托给 AnnotationConfigWebContextLoader loadContext 方法除外。在那里,除了刷新 WebApplicationContext,我做了所有事情。然后,在我的测试方法中,我手动构建并 运行 将容纳我的测试控制器(和无效配置)的 SpringBootApplication

感谢@viktor-sorokin 和@grzesuav 让我走上了正确的道路。

在您的 JUnit 测试中,您可以以编程方式启动 Spring 启动应用程序 - 类似于您的应用程序 class 的 main() 方法。在这样的测试中,您可以像往常一样断言异常。

  @Test
  public void test() {
    SpringApplication springApplication = new SpringApplication(MySpringBootApp.class);
    // Here you can manipulate the app's Environment, Initializers etc.     

    assertThatThrownBy(() -> {
      springApplication.run();
    }).isInstanceOf(Exception.class);
  }