loading table of contents...

Content Application Developer Manual / Version 2310

Table Of Contents 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.

class MyTest {
  @Configuration(proxyBeanMethods = false)
          value = {
                  "classpath:/com/mycompany" +
          reader = ResourceAwareXmlBeanDefinitionReader.class
  public static class LocalConfig {
    public static final String PROFILE = "MyTest";

    MockMvc mockMvc(WebApplicationContext wac) {
      return MockMvcBuilders.webAppContextSetup(wac).build();

  private MockMvc mockMvc;

  void test() throws Exception {
    Object 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

Your Internet Explorer is no longer supported.

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