Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {...
like image 979
ed4becky Avatar asked Dec 10 '22 09:12

ed4becky


2 Answers

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.

like image 87
glytching Avatar answered Jan 13 '23 11:01

glytching


You can create a separate application class for testing and exclude the components that are not required for tests:

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(
        type = FilterType.ASSIGNABLE_TYPE, 
        value = { ApplicationStartup.class, 
                 RealApplication.class }))

public class TestApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
}

Then in your SubmissionItemManagerTest class use the TestApplication class:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
public class SubmissionItemManagerTest {
    ...
}
like image 26
mjlowky Avatar answered Jan 13 '23 11:01

mjlowky