close

Filter

loading table of contents...

Content Application Developer Manual / Version 2304

Table Of Contents

4.3.9.2 Example - Testing Handlers

A controller/handler's behavior strongly depends on the concrete setup of the application context. For instance, the registered Converters or PropertyEditors might have an influence on its behavior as well as the currently used HandlerMapping. Thus, it might be useful to take this environment into account when testing a handler. Spring provides MockMvc for emulating servlet requests and by capturing a handler's ModelAndView result. See corresponding JavaDoc for details.

@SpringJunitWebConfig(MyTest.LocalConfig.class)
@ActiveProfiles(MyTest.LocalConfig.PROFILE)
class MyTest {
  @Configuration(proxyBeanMethods = false)
  @ImportResource(
          value = {
                  XmlRepoResources.HANDLERS,
                  "classpath:/com/mycompany" +
                  "/myproject/myproject-handlers-beans.xml"
          },
          reader = ResourceAwareXmlBeanDefinitionReader.class
  )
  @Import(XmlRepoConfiguration.class)
  @Profile(LocalConfig.PROFILE)
  public static class LocalConfig {
    public static final String PROFILE = "MyTest";

    @Bean
    @Scope(SCOPE_SINGLETON)
    MockMvc mockMvc(WebApplicationContext wac) {
      return MockMvcBuilders.webAppContextSetup(wac).build();
    }
  }

  @Autowired
  private MockMvc mockMvc;

  @Test
  void test() throws Exception {
    Object expectedModelBean =...;
    mockMvc
       .perform(
            MockMvcRequestBuilders
                    .get("/context/servlet/123")
                    .servletPath("/servlet")
                    .contextPath("/context")
       )
       .andExpect(MockMvcResultMatchers.status().isOk())
       .andExpect(MockMvcResultMatchers
                    .model()
                    .attribute(
                               HandlerHelper.MODEL_ROOT,
                               Matchers.equalTo(expectedModelBean)
                    )
       );
  }
}

Mind the test annotation @WebAppConfiguration which is required to have a WebApplicationContext available to build the MockMvc object.

MockMvcResultMatchers provides several matchers for validating the response. For more sophisticated analysis you can end the validation with andReturn() and get for example the ModelAndView from the returned MvcResult.

Search Results

Table Of Contents
warning

Your Internet Explorer is no longer supported.

Please use Mozilla Firefox, Google Chrome, or Microsoft Edge.