如何测试控制器方法是否将请求转发到特定URL?

时间:2017-11-15 14:17:58

标签: spring unit-testing mocking mockmvc

在我的Spring Boot应用程序中,我有以下控制器,只有一个方法可以将所有HTML5路由重定向到根URL **:

@Controller
public class RedirectController {

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

我应该如何正确测试它是否按预期工作?

调用content()类的MockMvcResultMatchers方法不起作用:

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

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

**我从this Spring tutorial开始了解此解决方案。

1 个答案:

答案 0 :(得分:2)

当我拨打andDo(print())课程的mockMvc时,我得到了以下结果:

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

这里我意识到Spring不会将return "forward:/";视为简单的String结果,而是将URL转发(在某种程度上非常明显),因此编写测试的正确方法是调用{{ 1}} .andExpect()作为参数的方法:

forwardedUrl("/")

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