Exclude a configuration when @WebMvcTest in Spring Boot 1.4

3.4k views Asked by At

I have a @SpringBootApplication class in java/ directory(same package) and another @SpringBootApplication class in test/ for mocking some auto-wired beans. There are several tests and which configuration is used varies from test to test.

And in a test class

@RunWith(SpringRunner.class)
@WebMvcTest(RecApiServerController.class)

throws

java.lang.IllegalStateException: Found multiple @SpringBootConfiguration annotated classes [Generic bean: class [com.xxx.MockedTestConfig]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/..direction.../target/test-classes/com/xxx/MockedTestConfig.class], Generic bean: class [com.xxx.MyApplication]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [/...direction.../target/classes/com/xxx/MyApplication.class]]

I just want to test routing of a controller.

How could I set a specific application configuration?

1

There are 1 answers

1
Stephane Nicoll On BEST ANSWER

You can't have two @SpringBootConfiguration (@SpringBootApplication) in the same package. @WebMvcTest searches automatically the source of configuration for you (see the doc). You can have a special @SpringBootConfiguration (or application) in a nested package of your test if you want to tune things but you can't have two in the same package.

I am not sure the doc is very explicit about that so we should probably clarify it.

Anyway, a custom @SpringBootApplication and slicing is a bit weird. @SpringMvcTest already takes care of only enabling what is necessary. If you want to mock some beans, you should not define that in a @SpringBootApplication. A regular @Configuration that you import is fine. We also have @MockBean to automatically mock things for you.