0

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?

margincall
  • 483
  • 1
  • 6
  • 24

1 Answers1

3

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.

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89
  • I changed `MockedTestConfig.class` to regular @Configuration and add `classes = { MyApplication.class, MockedTestConfig.class }` in @SpringBootTest, and all tests worked fine. They didn't before, so I changed it to @SpringBootApplication. I think the order in `classes` was wrong that time. Thank you. :) – margincall Dec 20 '16 at 09:04