92

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!

Naman
  • 27,789
  • 26
  • 218
  • 353
CRDamico
  • 923
  • 1
  • 6
  • 4
  • 2
    My answer to [this question](http://stackoverflow.com/q/11462697) explains why I think the do/when way of doing things is better than the when/then way. If you're just learning Mockito, then now is the time to read it. – Dawood ibn Kareem Oct 05 '16 at 19:22
  • 1
    Thank you that is really helpful, I've been learning/basing my Test files off of already existing ones within our legacy codebase and have seen both ways but I agree with your advice after running into the disadvantages of when/then twice already – CRDamico Oct 05 '16 at 20:18
  • 2
    Confuse future readers the syntax can. Consider carefully you should. – Jeff Bowman Oct 05 '16 at 20:19

1 Answers1

138

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.

Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • 4
    Thank you, that's exactly what I need, i specifically looked for that method and couldn't find it. It looks like it's working! – CRDamico Oct 05 '16 at 19:21