如何使用 MockMvc 作为 RequestBody 传递对象?

How can I pass a object using MockMvc as a 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' 语句失败。

我该如何解决这个问题?

在你的模拟中使用任何(Foo.class),而不是你的 if 应该匹配。

http://static.javadoc.io/org.mockito/mockito-core/2.19.0/org/mockito/ArgumentMatchers.html#any-java.lang.Class-