Search code examples
spring-bootmockitojunit5spring-boot-test

How to ignore ContextRefreshedEvent when SpringBootTest?


I'm struggling to find out how to ignore a class method, which should start a thread when SpringBootApplication is ready, during normal operation:

@EventListener
public void onApplicationEvent(ContextRefreshedEvent event) {

    this.start();
}

in case of testing I do not want such behavior, want to start it from test method. As far as i understand ContextRefreshedEvent is triggered by @SpringBootTest annotation on test class.


Solution

  • For testing the listener itself:

    You do not need @SpringBootTest for every test of Spring Boot application (I would argue that you want minimum of such tests actually as they load everything.)

    There are other options:

    • If you don't need anything from Spring: Unit test the service with Mockito (if it has dependencies you want to mock away).
    • Otherwise: Use slices - for example @JsonTest will autoconfigure ObjectMapper and other beans for working with JSON. There's quite a few of them so check documentation if there's any part of application you would like to be autoconfigured for your test.

    For excluding the listener from other @SpringBootTest tests:

    I see two options:

    • Mocking the listener bean away using @MockBeans.
    @SpringBootTest
    @MockBeans(@MockBean(Listener.class))
    public class SomeTest {
      // ...
    }
    
    • Executing tests inside a specific profile and mark the listener bean to be included only inside the default profile. (Or not inside the "test" profile.)
    @Component
    @Profile("default") // OR: @Profile("!test")
    public class Listener {
      // ...
    }
    
    @SpringBootTest
    @ActiveProfiles("test")
    public class SomeTest {
      // ...
    }
    

    You might need to extract the listener from the existing bean if you need the bean as a dependency for another service though.