Boyan Kushlev
Boyan Kushlev

Reputation: 1053

How to test if a controller method forwards the requests to a specific URL?

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.

Upvotes: 3

Views: 4958

Answers (1)

Boyan Kushlev
Boyan Kushlev

Reputation: 1053

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.

Upvotes: 7

Related Questions