Josh Ghiloni
Josh Ghiloni

Reputation: 1300

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

I've got a situation where we want to inspect Spring MVC code on startup and throw an exception (thus causing the ApplicationContext to to fail) when certain conditions aren't met.

Is there a way to instrument a JUnit test to catch Spring startup (specifically, Spring Boot in most cases) exceptions so that they don't cause a test failure? I basically want to fail the test if the exception doesn't happen.

Upvotes: 2

Views: 2887

Answers (2)

Peter Wippermann
Peter Wippermann

Reputation: 4579

In your JUnit test you can start your Spring Boot app programmatically - similar to the main() method of your Application class. In such a test you can assert Exceptions as you'd normally do.

  @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);
  }

Upvotes: 9

Josh Ghiloni
Josh Ghiloni

Reputation: 1300

I was able to solve the problem yesterday. Because the default SmartContextLoader classes like AnnotationConfigWebContextLoader and SpringApplicationContextLoader, which are pulled in by annotations, fully load the ApplicationContext, I couldn't catch any exceptions there.

The solution I came up with--and I'm sure there are much more elegant solutions out there--was to create my own implementation of SmartContextLoader that delegated everything to a AnnotationConfigWebContextLoader except the loadContext method. There, I did everything except refresh the WebApplicationContext. Then, inside my test method, I manually built and ran the SpringBootApplication that would hold my test Controller (and invalid configuration).

Thanks to both @viktor-sorokin and @grzesuav for getting me started down a correct path.

Upvotes: 0

Related Questions