Tag Archives: exclude

Exclude beans from tests in Spring Boot

springboot
Running unit tests bootstraps, for example, scheduling tasks (EnableScheduling, Scheduled).
To exclude automatic start up auto-configuration beans with annotation you can follow next instruction:

1. Create annotation:

public @interface ExcludeFromTests {
}

2. Annotate with it Application and Scheduled beans (or what you want to be skipper during tests):

@SpringBootApplication
@EnableAsync
@EnableScheduling
@ExcludeFromTests
public class BackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BackendApplication.class, args);
    }
}
@Component
@ExcludeFromTests
public class AppScheduler {

    @Scheduled(fixedRateString = "1000000")
    public void do() {
      //...
    }
}

3. Create TestApplication class for tests and add ComponentScan.Filter:

@SpringBootApplication
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromTests.class))
public class TestBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestBackendApplication.class, args);
    }
}

4. Say Spring boot to use TestApplication class in tests:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestBackendApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class SomeTest {
  
  @Test
  public void test1() throws Exception {
    //...
  }
}

5. Profit! -)

See also:
- http://www.concretepage.com/spring/spring-component-scan-include-and-exclude-filter-example-using-javaconfig-and-xml-with-annotation-assignable-aspect-and-regex-filter-types
- http://stackoverflow.com/questions/18992880/exclude-component-from-componentscan
- http://stackoverflow.com/questions/10725192/exclude-subpackages-from-spring-autowiring
- http://stackoverflow.com/questions/25550494/componentscan-excludefilters-not-working-in-spring-4-0-6-release
- http://farenda.com/spring/spring-component-scan-exclude/