Mockito - thenCallRealMethod() on void function

CRDamico picture CRDamico · Oct 5, 2016 · Viewed 23.6k times · Source

I have been running into a problem when trying to write a JUnit test case and am relatively new to Mockito.

I have a function of a class that I am mocking, this function happens to be of a void return type. When calling this function from my mocked class it is my understanding (and debugging experience) that it does NOT call the original function. In order to overcome this, I have attempted to use a "when" with a "thenCallRealMethod()".

when(instance.voidFunction()).thenCallRealMethod();

The "voidFunction" is full of logic that I do NOT want to fire. I have extracted these into when statements to avoid that. I have read that I should use the format of doReturn().when().voidFunction(), however doing this does not call the real method.

It was also my understanding that I could not use a Spy here, due to the fact that I do not want the voidFunction() called before the "when" statements. Any help is appreciated I apologize if this is a very easy solution as my understanding of mockito isn't very great despite reading quite a bit. Thanks!

Answer

Jeff Bowman picture Jeff Bowman · Oct 5, 2016

The when syntax won't work with a void method (it won't fit within the when), and doReturn doesn't apply when there's no return value. doCallRealMethod is likely the answer you want.

doCallRealMethod().when(instance).voidFunction();

Bear in mind that when calling a real method on a mock, you may not get very realistic behavior, because unlike with spies mocked objects will skip all constructor and initializer calls including those to set fields. That means that if your method uses any instance state at all, it is unlikely to work as a mock with doCallRealMethod or thenCallRealMethod. With a spy, you can create a real instance of your class, and then the Mockito.spy method will copy that instance state over to make for a more realistic interaction.