How to mock methods with void return type?
I implemented an observer pattern but I can\'t mock it with Mockito because I don\'t know how.
And I tried to fin
In Java 8 this can be made a little cleaner, assuming you have a static import for org.mockito.Mockito.doAnswer
:
doAnswer(i -> {
// Do stuff with i.getArguments() here
return null;
}).when(*mock*).*method*(*methodArguments*);
The return null;
is important and without it the compile will fail with some fairly obscure errors as it won't be able to find a suitable override for doAnswer
.
For example an ExecutorService
that just immediately executes any Runnable
passed to execute()
could be implemented using:
doAnswer(i -> {
((Runnable) i.getArguments()[0]).run();
return null;
}).when(executor).execute(any());