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.

Boyan Kushlev
  • 1,043
  • 1
  • 18
  • 35

1 Answers1

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.

Boyan Kushlev
  • 1,043
  • 1
  • 18
  • 35