Mockito - thenCallRealMethod() on void function

Unit TestingJunitMockingMockitoVoid

Unit Testing Problem Overview


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!

Unit Testing Solutions


Solution 1 - Unit Testing

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCRDamicoView Question on Stackoverflow
Solution 1 - Unit TestingJeff BowmanView Answer on Stackoverflow