3

In my Spring Boot application I have the following controller with a single method that redirects all HTML5 routes to the root URL**:

@Controller
public class RedirectController {

  @RequestMapping(value = "/**/{path:[^\\.]*}")
  public String redirect() {
    return "forward:/";
  }
}

How should I properly test that it works as expected?

Calling the content() method of the MockMvcResultMatchers class doesn't work:

  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(content().string("forward:/"));
  }

>>> java.lang.AssertionError: Response content 
>>> Expected :forward:/
>>> Actual   :

** I found out about this solution from following this Spring tutorial.

1 Answer 1

7

When I called the andDo(print()) of the mockMvc class I got the following result:

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = {}
     Content type = null
             Body = 
    Forwarded URL = /
   Redirected URL = null
          Cookies = []

Here I realized that Spring doesn't treat return "forward:/"; as a simple String result, but a URL forwarding (in a way it's pretty obvious), so the proper way to write the test is by calling the .andExpect() method with forwardedUrl("/") as an argument:

  @Test
  public void givenPathWithoutDotShouldReturnString() throws Exception {
    this.mockMvc.perform(get("/somePath"))
        .andExpect(forwardedUrl("/"));
  }

The forwardedUrl() method comes from org.springframework.test.web.servlet.result.MockMvcResultMatchers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.