9

I am using Spring Boot 1.4.3.RELEASE and want to exclude some components from being scanned when running the tests.

@RunWith(SpringRunner.class)
@SpringBootTest
@ComponentScan(
        basePackages = {"com.foobar"},
        excludeFilters =  @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {AmazonKinesisRecordChecker.class, MyAmazonCredentials.class}))
public class ApplicationTests {

    @Test
    public void contextLoads() {
    }

}

Despite the filters, when I run the test the unwanted components are loaded and Spring Boot crashes as those classes require an AWS environment to work properly:

2017-01-25 16:02:49.234 ERROR 10514 --- [           main] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'amazonKinesisRecordChecker' defined in file 

Question: how can I make the filters working?

Javide
  • 2,477
  • 5
  • 45
  • 61
  • @SpringBootTest(classes=<> ) . Docs : http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/context/SpringBootTest.html – Barath Jan 25 '17 at 05:18
  • @Barath Are you saying there is only a way to include classes, but not to exclude them when in Spring Boot Test? – Javide Jan 25 '17 at 05:32
  • No I am not saying so, you can use WebMvcTest to exclude filters Doc :http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/autoconfigure/web/servlet/WebMvcTest.html – Barath Jan 25 '17 at 06:38
  • for your information : http://stackoverflow.com/questions/26698071/how-to-exclude-autoconfiguration-classes-in-spring-boot-junit-tests – Barath Jan 25 '17 at 06:46
  • 2
    `@ComponentScan` on a test class is not working nor useful. It will only work on `@Configuration` classes. Next to that even if it would be accepted it wouldn't work. As there would be an additional `@ComponentScan` on your application class one would detect the component and the other wouldn't. With the same result. – M. Deinum Jan 25 '17 at 12:54

1 Answers1

5

What you need is, not to exclude them but to mock them instead, using @MockBean. As shown below

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
    @MockBean
    AmazonCredentials amazonCredentials;

    @Test
    public void contextLoads() {
    }
}

This way you will let Spring Context know that you want to mock the AmazonCredentials bean. Sometimes, excluding filters is a bit tricky to work with.

Hope this helps! I would love to explore if we have another way to get this done.

dagra
  • 589
  • 4
  • 20