6

When using mocks for unit testing, I often encounter the need to check whether a certain method of the mock is invoked with proper arguments. This means that I have to somehow find a way to peek into what gets passed to the method in question. In Spock this can be done using something like:

1 * serviceMock.operate(*_) >> { args ->
    def argument = args[0]
    assert expectedValue = argument.actualValue
}

With Mockito (and JUnit), the only way I think this can be done is by using doAnswer and verify, something like:

doAnswer(new Answer() {
  //check arguments here
}).when(service).operate(any(Data.class));

Then I have to verify that the operation actually gets called with:

verify(service).operate(any(Data.class));

The code above, however, interferes with doAnswer as if it's an actual call to the method in question. How do I work around this so that I can both verify that the method is called, and verify that the arguments it gets are correct?

Psycho Punch
  • 6,418
  • 9
  • 53
  • 86

1 Answers1

1

Mockito verifies argument values in natural java style: by using an equals() method. This is also the recommended way of matching arguments because it makes tests clean & simple.

ArgumentCaptor<Data> argument = ArgumentCaptor.forClass(Data.class);
verify(service).operate(argument.capture());
assertEquals("John", argument.getValue().getDataName());

more refer here

I hope this will be helpful