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 {...
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
.
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 {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With