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

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

I tried:

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


        
13条回答
  •  星月不相逢
    2020-12-01 02:26

    If the issue is that your SpringBootApplication/Configuration you are bringing in is component scanning the package your test configurations are in, you can actually remove the @Configuration annotation from the test configurations and you can still use them in the @SpringBootTest annotations. For example, if you have a class Application that is your main configuration and a class TestConfiguration that is a configuration for certain, but not all tests, you can set up your classes as follows:

    @Import(Application.class) //or the specific configurations you want
    //(Optional) Other Annotations that will not trigger an autowire
    public class TestConfiguration {
        //your custom test configuration
    }
    

    And then you can configure your tests in one of two ways:

    1. With the regular configuration:

      @SpringBootTest(classes = {Application.class}) //won't component scan your configuration because it doesn't have an autowire-able annotation
      //Other annotations here
      public class TestThatUsesNormalApplication {
          //my test code
      }
      
    2. With the test custom test configuration:

      @SpringBootTest(classes = {TestConfiguration.class}) //this still works!
      //Other annotations here
      public class TestThatUsesCustomTestConfiguration {
          //my test code
      }
      

提交回复
热议问题