Mockito – thenCallRealMethod() on void function

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)