Search code examples
javaspring-bootjunitspring-boot-testspringrunner

Exclude ApplicationStartup Event listener when testing


I recently added an ApplicationStartup class to my SpringBoot project

@Component
public class ApplicationStartup
    implements ApplicationListener<ApplicationReadyEvent> { ...

It implements ApplicationListener.

Now when I run my old JUNit tests that have nothing to do with that class, The testrunner tries to Run my StartupListener, which is neither necessary not appropriate in these cases.

How do I skip the ApplicationListener when my tests initialize?

@RunWith(SpringRunner.class)
@SpringBootTest
public class SubmissionItemManagerTest {...

Solution

  • You can mock your ApplicationStartup class

    Add this declaration to your test case:

    @MockBean
    private ApplicationStartup applicationStartup
    

    This will create a mocked instance of ApplicationStartup and mark it as @Primary in your test context thereby replacing the actual instance ofApplicationStartup.