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

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

I tried:

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


        
13条回答
  •  误落风尘
    2020-12-01 02:35

    I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.

    /**
    * Type-safe alternative to {@link #basePackages} for specifying the packages
    * to scan for annotated components. The package of each class specified will be scanned.
    * Consider creating a special no-op marker class or interface in each package
    * that serves no purpose other than being referenced by this attribute.
    */
    Class[] basePackageClasses() default {};

    1. Create a package for your spring tests, ("com.example.test").
    2. Create a marker interface in the package as a context qualifier.
    3. Provide the marker interface reference as a parameter to basePackageClasses.

    Example


    IsolatedTest.java

    package com.example.test;
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ComponentScan(basePackageClasses = {TestDomain.class})
    @SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
    public class IsolatedTest {
    
         String expected = "Read the documentation on @ComponentScan";
         String actual = "Too lazy when I can just search on Stack Overflow.";
    
          @Test
          public void testSomething() throws Exception {
              assertEquals(expected, actual);
          }
    
          @ComponentScan(basePackageClasses = {TestDomain.class})
          public static class Config {
          public static void main(String[] args) {
              SpringApplication.run(Config.class, args);
          }
        }
    }
    
    ...
    

    TestDomain.java

    package com.example.test;
    
    public interface TestDomain {
    //noop marker
    }
    

提交回复
热议问题