我有一个普通的 spring @Controller,它采用 URL 编码的字符串作为参数:
@RequestMapping(value = "/wechat/browser", method = GET)
public void askWeChatWhoTheUserIs(@RequestParam(name = "origin") String origin,
HttpServletResponse response) throws IOException {
//omitted codes
}
当我调试 Spring Boot 应用程序并使用浏览器测试端点时:
curl http://localhost:8080/wechat/browser\?origin\=http%3A%2F%2Fwww.example.com%2Findex.html%3Fa%3Db%23%2Froute
origin
自动解码,等于 http://www.example.com/index.html?a=b#/route
但是当我写了一个 spring mvc 测试时:
@RunWith(SpringRunner.class)
@WebMvcTest(WeChatOauthController.class)
public class WeChatOauthControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void itShouldRedirectToWeChatToFinishOauthProtocol() throws Exception {
String origin = "http://www.example.com/index.html?a=b#/route";
String encodedOrigin = URLEncoder.encode(origin, "UTF-8");
this.mvc.perform(get("/wechat/browser")
.param("origin", encodedOrigin))
.andDo(print())
//omitted codes
}
}
当我调试这个测试和 Controller 时,
origin
这次没有解码。只是想知道为什么它在这两种情况下表现不同。
最佳答案
当使用 Spring MVC 测试框架提供请求参数时,不需要手动编码参数的值,因为没有物理 HTTP 请求。
所以,只需使用 original
测试中的原始值,它应该可以正常工作。
换句话说,使用这个:
@RunWith(SpringRunner.class)
@WebMvcTest(WeChatOauthController.class)
public class WeChatOauthControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void itShouldRedirectToWeChatToFinishOauthProtocol() throws Exception {
this.mvc.perform(get("/wechat/browser")
.param("origin", "http://www.example.com/index.html?a=b#/route"))
.andDo(print())
//omitted codes
}
}
关于spring-mvc - 与 spring @RequestParam 不一致的自动解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40383940/