Boy*_*lev 2 spring unit-testing mocking mockmvc
在我的 Spring Boot 应用程序中,我有以下控制器,它使用一个方法将所有 HTML5 路由重定向到根 URL**:
@Controller
public class RedirectController {
@RequestMapping(value = "/**/{path:[^\\.]*}")
public String redirect() {
return "forward:/";
}
}
Run Code Online (Sandbox Code Playgroud)
我应该如何正确测试它是否按预期工作?
调用类的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 :
Run Code Online (Sandbox Code Playgroud)
** 我从这个 Spring 教程中发现了这个解决方案。
当我打电话给andDo(print())了的mockMvc阶级,我得到了以下结果:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = /
Redirected URL = null
Cookies = []
Run Code Online (Sandbox Code Playgroud)
在这里,我意识到 Spring 不会将return "forward:/";结果视为简单的 String 结果,而是将 URL 转发(在某种程度上很明显),因此编写测试的正确方法是将.andExpect()方法forwardedUrl("/")作为参数调用:
@Test
public void givenPathWithoutDotShouldReturnString() throws Exception {
this.mockMvc.perform(get("/somePath"))
.andExpect(forwardedUrl("/"));
}
Run Code Online (Sandbox Code Playgroud)
该forwardedUrl()方法来自org.springframework.test.web.servlet.result.MockMvcResultMatchers.
| 归档时间: |
|
| 查看次数: |
3197 次 |
| 最近记录: |