gpt4 book ai didi

java - 测试 Controller 方法失败并抛出 HttpMessageNotReadableException

转载 作者:行者123 更新时间:2023-12-01 11:12:01 25 4
gpt4 key购买 nike

我有以下 mock

mockMvc.perform(get("/bk/getBks?sd="+1262296800000L+"&nod=3"))
.andDo(print());

这是我的 Controller

@RestController
@RequestMapping("/bk")
public class BkController {
@RequestMapping(value = "/getBks", method = RequestMethod.GET)
public ResponseEntity<List<BkDTO>> getBks(@Valid @RequestBody GetBksForm form, BindingResult result) throws ... {
return ...;
}

}

还有我的验证表单

public class GetBksForm {

@Min(1000000000000L)
private Long sd;

@Min(1)
private int nod;

setters and getters
}

问题是它不断抛出以下异常,我不明白为什么。

MockHttpServletRequest:
HTTP Method = GET
Request URI = /bk/getBks
Parameters = {sd=[1262296800000], nod=[3]}
Headers = {}

Handler:
Type = com.ihbs.booking.BkController
Method = public org.springframework.http.ResponseEntity<java.util.List<com.ihbs.bk.BkDTO>> com.ihbs.bk.BkController.getBks(com.ihbs.bk.GetBksForm,org.springframework.validation.BindingResult) throws ...

Async:
Async started = false
Async result = null

Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException

ModelAndView:
View name = null
View = null
Model = null

FlashMap:

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

我看起来它找到了处理程序,但它不知道如何读取请求,而且我不明白为什么。

最佳答案

根据RequestBody javadoc:

Annotation indicating a method parameter should be bound to the body of the web request. The body of the request is passed through an HttpMessageConverter to resolve the method argument depending on the content type of the request. Optionally, automatic validation can be applied by annotating the argument with @Valid.

因此,如果您想使用 RequestBody,应将请求参数以 JSON 格式放入请求正文部分,并按如下所示更改单元测试:

mvc.perform(
get("/bk/getBks").content("{\"sd\": \"1262296800000L\", \"nod\":\"3\"}").contentType(APPLICATION_JSON)).andDo(print());
}

以这种方式传输域对象比通过请求参数传输更好。

<小时/>

更新

如果将请求参数绑定(bind)到域对象,只需删除@RequestParam,Spring就会将请求参数绑定(bind)到域对象。

关于java - 测试 Controller 方法失败并抛出 HttpMessageNotReadableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32235335/

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