How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

前端 未结 13 1170
名媛妹妹
名媛妹妹 2020-12-01 01:51

I tried:

@RunWith(SpringJUnit4ClassRunner.class)
@EnableAutoConfiguration(exclude=CrshAutoConfiguration.class)
@SpringApplicationConfiguration(classes = Appl         


        
13条回答
  •  臣服心动
    2020-12-01 02:24

    I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

    Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

    However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

    My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

    1. RepoIntegrationTest.java
    2. TestRepoConfig.java

    where RepoIntegrationTest.java has

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringApplicationConfiguration(classes = TestRepoConfig.class)
    public class RepoIntegrationTest {
    

    and TestRepoConfig.java has

    @SpringBootApplication(exclude = SecurityAutoConfiguration.class)
    public class TestRepoConfig {
    

    It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

提交回复
热议问题