5

I want to test my Controller using @WebMvcTest and mock the dependencies, but Spring Boot's AutoConfiguration loads my Couchbase (Spring Data) configuration automatically. Couchbase is not available on some platforms which run the test, so the Test class will throw an Exception. How can I exclude some classes from the AutoConfiguration mechanism?

I tried the excludeFilters option of @WebMvcTest and @ActiveProfile to load another Application Context, but that didn't work.

Test configuration:

@RunWith(SpringRunner.class)
@WebMvcTest(value = ExchangeJobImportController.class, excludeFilters = @ComponentScan.Filter(classes = CouchbaseConfiguration.class))
@ActiveProfiles("test")
public class ExchangeJobImportControllerTest {
  ...
}

Couchbase Configuration:

@Configuration
@EnableCouchbaseAuditing
@EnableConfigurationProperties({CouchbaseProperties.class})
@EnableCouchbaseRepositories(basePackages = "com....")
public class CouchbaseConfiguration extends AbstractCouchbaseConfiguration {
  ...
}
janb
  • 1,057
  • 1
  • 9
  • 11

2 Answers2

1

After some more struggling I found the solution: exclude the @SpringBootApplication annotated class in the @WebMvcTest annotation:

@RunWith(SpringRunner.class)
@WebMvcTest(value = ExchangeJobImportController.class, excludeAutoConfiguration = Application.class, secure = false)
@ActiveProfiles("localhost")
public class ExchangeJobImportControllerTest {
  ...
}

For the record, I am using Spring Boot 1.5.1.RELEASE

janb
  • 1,057
  • 1
  • 9
  • 11
  • Struggle to find this configuration for a Filter that fail for one hour!! Thank you! – Antimo Jan 29 '18 at 16:43
  • FYI: I'm using Spring boot 3.1.0 and the `secure` flag doesn't exist anymore, it was removed but i don't know exactly since which version – Hassen Gaaya Jul 11 '23 at 13:11
0

I know it's been some time but I suppose the reason why the @ComponentScan.Filter solution doesn't work is that it looks for an annotation type for the classes field by default.

So, setting the FilterType as ASSIGNABLE_TYPE should work in your case:

@ComponentScan.Filter(
    type = FilterType.ASSIGNABLE_TYPE,
    classes = CouchbaseConfiguration.class
)
Yavuz Tas
  • 344
  • 3
  • 16