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

Jos*_*oni 1 java junit spring spring-mvc spring-boot

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

有没有办法检测 JUnit 测试以捕获 Spring 启动(特别是大多数情况下的 Spring Boot)异常,以便它们不会导致测试失败?如果异常没有发生,我基本上希望测试失败。

Pet*_*ann 6

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

  @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);
  }
Run Code Online (Sandbox Code Playgroud)