0

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?

katiex7
  • 863
  • 12
  • 23

1 Answers1

1

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-

Master Slave
  • 27,771
  • 4
  • 57
  • 55
  • Oh by the way, Is there a way to avoid directly creating a Foo object totally, without Dependency Injection? OR do I still need this due to mockMvc's post method. Because if I do something like mockMvc.perform(post("").contentType(APPLICATION_JSON_UTF8).content(toJsonString(any(Foo.class))) then there are reflection issues – katiex7 Jul 04 '18 at 23:21