在我的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开始了解此解决方案。
答案 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()
。