Prevent Application / CommandLineRunner classes from executing during JUnit testing

前端 未结 7 1495
既然无缘
既然无缘 2020-12-07 22:47

If in your TestCase class there is this annotations:

@SpringApplicationConfiguration(classes = {Application.class})

this will cause the

7条回答
  •  独厮守ぢ
    2020-12-07 23:05

    You can define a test configuration in the same package as your application that looks exactly the same, except that it excludes beans implementing CommandLineRunner. The key here is @ComponentScan.excludeFilters:

    @Configuration
    @ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class))
    @EnableAutoConfiguration
    public class TestApplicationConfiguration {
    }
    

    Then, just replace the configuration on your test:

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(classes = TestApplicationConfiguration.class)
    public class SomeApplicationTest {
        ...
    }
    

    No CommandLineRunner will be executed now, because they are not part of the configuration.

提交回复
热议问题