Reputation: 7169
I have a rather large Spring Boot application with numerous configuration files that I would like to test. I would like to be able to test the fully configured application, but with single beans excluded in each test as good negative controls. For example, I'd like to exclude individual WebMvcConfigurer
beans, such as a CORS filter, to test that configuration is actually causing the tests to pass, and not just poor test writing. Is it possible to exclude or overwrite beans during test initialization, or through additional configuration?
Upvotes: 0
Views: 1909
Reputation: 3955
You could add a BeanFactoryPostProcessor that removes the bean from the beanfactory (this happens before the bean is instantiated).
https://docs.spring.io/spring-framework/docs/5.0.6.RELEASE/javadoc-api/org/springframework/beans/factory/config/BeanFactoryPostProcessor.html
You can add such a postprocessor in a nested @TestConfiguration
class of your test class, then this bean gets loaded only for this test class in addition to all your normal config.
But honestly this is getting quite convoluted, and that might be a sign that your design could be improved somehow...
Upvotes: 0
Reputation: 3955
You can annotate your test with @TypeExcludeFilters
https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/api/org/springframework/boot/test/autoconfigure/filter/TypeExcludeFilters.html
I believe you need to write your own TypeExcludeFilter implementation, but it is quite straightforward. Note that the filter only gets applied to component-scanned Beans (not autoconfiguration beans)
You can also have a look at the "test slices" that Spring Boot provides: https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-autoconfigured-tests
For many of the slice annotations (e.g. @WebMvcTest
) you can add includes and excludes in a more declarative way.
If you want to exclude some autoconfiguration, you can use the @ImportAutoConfiguration
annotation: https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/autoconfigure/ImportAutoConfiguration.html
Upvotes: 1