Exclude ApplicationStartup Event listener when testing

北城余情 提交于 2019-12-24 06:46:19

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/46597149/exclude-applicationstartup-event-listener-when-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!