Skip to content
Advertisement

How to exclude a @Configuration class when using @WebMvcTest with spring-boot?

I am writing junits for a rest controller. I want only minimal context to be loaded which is related to the controller and I think that is how @WebMvcTest loads the context. But the junit is loading complete Spring context and it is failing as some of the beans can not be created.

I have searched and read through many questions on stackoverflow and none of the solutions worked to exclude specific configuration. How can I load a minimal context when writing junits for controllers? Or is there any way to exclude some configuration classes? I am using Spring-boot 2.2.2.RELEASE, Java 8 and Junit 4.

Junit (where I have tried to exclude loading of some beans and configurations but it doesn’t work):

JavaScript

Controller

JavaScript

Configuration class which I want to exclude from context loading

JavaScript

Spring boot main class:

JavaScript

Advertisement

Answer

Your use of @ComponentScan has disabled the filters that are used by @WebMvcTest to limit the types of components that are found by scanning.

You should remove @ComponentScan from your main application class and use the basePackages attribute on @SpringBootApplication instead.

You should also move @EnableJms and @EnableAspectJAutoProxy to a separate @Configuration class so that they are not enabled when using @WebMvcTest. Alternatively, you may be able to remove them entirely as they are covered by Spring Boot’s auto-configuration.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement