gpt4 book ai didi

spring-mvc - 使用 MvcMock 将 HttpServletRequest 设置为测试方法参数

转载 作者:行者123 更新时间:2023-12-01 00:46:50 28 4
gpt4 key购买 nike

我正在为具有方法签名的 Controller 方法之一编写junit,如下所示:

@RequestMapping(value="/getTokenizedURL.json",method=RequestMethod.POST)
@ResponseBody
public ResponseData getTokenizedURL(@RequestBody final RequestData requestData, final HttpServletRequest request) throws CustomException

我需要使用 MockMvc 调用此方法,并且可以使用以下方法调用:
mockMvc.perform(post("/user/getTokenizedURL.json")
.contentType(MediaType.APPLICATION_JSON)
.content(json))
.andDo(print())
.andExpect(status().isOk());

但问题是我无法设置 HttpServletRequest使用模拟 mvc 调用原始方法时的参数。无设置 HttpServletRequest争论,我的测试给出了问题,因为它是原始方法所必需的和使用的。

请让我知道我应该如何设置相同的。谢谢!

最佳答案

这个想法是你不应该需要。

MockMvcRequestBuilders#post(..) 返回 MockHttpServletRequestBuilder 这使您可以使用所需的任何值构建请求。这些将反射(reflect)在 HttpServletRequest 中传递给您的处理程序方法。

例如,您使用

.contentType(MediaType.APPLICATION_JSON)

这将设置 content-type请求的头部。在您的处理程序方法中,如果您这样做了
request.getHeader("content-type");

你会得到一个相应的 StringMediaType.APPLICATION_JSON .
MockHttpServletRequestBuilder请求的每个部分都有“setter”。

关于spring-mvc - 使用 MvcMock 将 HttpServletRequest 设置为测试方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33768181/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com