Reputation: 1370
I have more than one controllers in my Spring boot application. I have written UnitTest using @WebMvcTest without defining specific controller class. How can I check Controller class loaded in the current UnitTest context
Upvotes: 0
Views: 447
Reputation: 12021
As you get a Spring Test Context when running @WebMvcTest
, you can try to inject your controller (they are also Spring Beans) or check if the bean is present inside the WebApplicationContext
.
The following test uses both approaches:
@WebMvcTest(MyController.class)
class MyControllerTest {
@Autowired
private MockMvc mockMvc;
@Autowired(required = false)
private OtherController otherController;
@Autowired(required = false)
private MyController myController;
@Autowired
private WebApplicationContext webApplicationContext;
@Test
void test() throws Exception {
assertNull(otherController);
assertNotNull(myController);
assertNotNull(webApplicationContext.getBean(MyController.class));
assertThrows(NoSuchBeanDefinitionException.class, () -> webApplicationContext.getBean(OtherController.class));
}
}
You can also remove required=false
from @Autowired
and then your test will immediately fail as it can't inject the requested controller bean.
Upvotes: 2