spring - 如何使用 MockMvc 作为 RequestBody 传递对象?
问题描述
所以这是我在代码中所面临的场景和问题
// the call that I am making in my test, please note that myService is a Mocked object
Foo foo = new Foo();
when(myService.postFoo(foo)).thenReturn(true);
mockMvc.perform(post("/myEndpoint")
.contentType(APPLICATION_JSON_UTF8)
.content(toJsonString(foo))
.andExpect(status().isAccepted());
// this is the controller method that get's called
@PostMapping("/myEndpoint")
@ResponseStatus(code = HttpStatus.ACCEPTED)
public String postFoo(@RequestBody Foo foo) {
if (myService.postFoo(foo)) {
return "YAY";
}
return "" + 0 / 0;
}
我面临的问题是mockMvc的post传入的foo是Foo的一个新实例,所以myService.postFoo(foo)的if语句失败。我假设引擎使用我的 foo 对象的 jsonString 来创建一个在字段方面相同但不同的对象的新对象,从而使“if”语句失败。
我该如何解决这个问题?
解决方案
在你的模拟中使用 any(Foo.class) ,而不是你的 if 应该匹配。
推荐阅读
- lua - Lua Love2D 错误:语法错误:main.lua:1: '=' 预期
- java - 是否可以检查 Dialog 在活动中是否可见?
- jenkins - 在 Jenkins 中构建远程多分支管道
- php - 如何在 SQL 中获得最低的唯一出价
- data-visualization - 是否有免费的物联网设备地图和 GPS 记录器服务?(如 Azure IoT Central 中的 Azure Maps)
- vue.js - 使用 axios 将 vue.js 数据对象发送到后端
- jquery - i18next jquery 翻译另一个元素内的元素
- javascript - 手动测试 JavaScript Number.toLocaleString()
- caffe - PRelue 不支持 mmdnn?
- json - 带有 JSON 字段的 Amazon Cloudwatch 日志见解