katiex7
katiex7

Reputation: 913

How can I pass a object using MockMvc as a RequestBody?

So here is the scenario and problem I am facing explained in code

// 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; 
}

The problem I am facing is that the foo that is passed in by mockMvc's post is a new instance of Foo, so the if statement for myService.postFoo(foo) fails. I am assuming that the engine used the jsonString of my foo object to create a new one that is field wise identical, however a different object, thus making that 'if' statement fails.

How can I work around this?

Upvotes: 0

Views: 1594

Answers (1)

Master Slave
Master Slave

Reputation: 28559

Use any(Foo.class) in your mock, than your if should match.

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

Upvotes: 1

Related Questions