How to use @ComponentScan together with test-specific ContextConfigurations in SpringJunit4TestRunner?

后端 未结 4 1918
心在旅途
心在旅途 2021-01-01 14:32

I am testing a Spring Boot application. I have several test classes, each of which needs a different set of mocked or otherwise customized beans.

Here is a sketch of

4条回答
  •  滥情空心
    2021-01-01 15:16

    You may use additional explicit profiles to avoid such test configurations to be picked up (as suggested in another answer). I also did it and even created some library support for that.

    However, Spring-Boot is clever and it has a built-in "type filter" to resolve this issue automatically. For this to work, you need to remove your @ComponentScan annotation, which would find your test configurations, and let the @SpringBootApplication do the work. In your example, just remove this:

    @SpringBootApplication
    @ComponentScan(
        basePackageClasses = {
                MyApplication.class,
                ImportantConfigurationFromSomeLibrary.class,
                ImportantConfigurationFromAnotherLibrary.class})
    

    and replace it with:

    @SpringBootApplication(scanBasePackageClasses= {
                MyApplication.class,
                ImportantConfigurationFromSomeLibrary.class,
                ImportantConfigurationFromAnotherLibrary.class})
    

    You may also need to annotate your test as @SpringBootTest. This should avoid auto-scanning any inner-class configurations (and components) except for those residing in the current test.

提交回复
热议问题