ed4becky
ed4becky

Reputation: 1630

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 {...

Upvotes: 5

Views: 10227

Answers (2)

mjlowky
mjlowky

Reputation: 1223

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 {
    ...
}

Upvotes: 5

glytching
glytching

Reputation: 47935

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.

Upvotes: 11

Related Questions