首页 > 解决方案 > 如何使用 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”语句失败。

我该如何解决这个问题?

标签: springspring-mvcspring-bootmockitomockmvc

解决方案


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

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


推荐阅读