Mock void Method, Static Method - ParadiseGuo/JavaLearning GitHub Wiki

doReturn()|doThrow()| doAnswer()|doNothing()|doCallRealMethod() family of methods

Stubbing void methods requires a different approach from when(Object) because the compiler does not like void methods inside brackets... Use doThrow() when you want to stub a void method with an exception:

doThrow(new RuntimeException()).when(mockedList).clear();

//following throws RuntimeException:

mockedList.clear();

You can use doThrow(), doAnswer(), doNothing(), doReturn() and doCallRealMethod() in place of the corresponding call with when(), for any method. It is necessary when you

  • stub void methods
  • stub methods on spy objects (see below)
  • stub the same method more than once, to change the behaviour of a mock in the middle of a test. but you may prefer to use these methods in place of the alternative with when(), for all of your stubbing calls. Read more about these methods:

doReturn(Object)

doThrow(Throwable...)

doThrow(Class)

doAnswer(Answer)

doNothing()

doCallRealMethod()

These methods can be combined like:

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Mock Util Class with Static Methods:

use PowerMockito.mockStatic(instance);