Using runner lets you save a little bit of coding (no need for
@Before method). On the other hand using a runner is sometimes not possible, i.e. when you are already using one, like
@Mock and @InjectMocks
@Mock creates a mock on each test method run, and @InjectMocks will pass mocks to any matching setters or constructors
@Captor private ArgumentCaptor<TargetClass> targetClassCaptor; verify(myClass).doSomething(targetClassCaptor.capture()); TargetClass= targetClassCaptor.getValue(); assertThat(...); assertTrue(...);
Stubbing void methods
We face a lot of scenarios in our applications where we need to stub void methods. With void methods, stubbing is slightly different. We cannot use void methods in the when() call.
The alternative syntax is:
We can also test exception handling. How would my code handle if an exception is thrown by void methods
We can also set the behaviour of a void method to do nothing when called. This is not possible for non-void methods:
Why when() does not work for void methods:
Take a look at the syntax of when():
Notice that the method is called inside brackets. Compiler does not like void method inside brackets!!
The two ‘when()’ are different syntax.
Notice that the when() for a non-void method stubbing takes in a methodCall as parameter, whereas the when() in void method stubbing takes in a mock object.
return Argument that is passed in:
If you have Mockito 1.9.5, there is a new static method that can make the
Answer object for you. You need to write something like
Note that the
returnsFirstArg() method is static in the
AdditionalAnswers class, which is new to Mockito 1.9.5; so you’ll need the right static import.