Search code examples
spring-boot-test

How to check intended controllers are loaded in WebMvcTest in Spring Boot Unit Test


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


Solution

  • 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.