There are smiliar questions to this but they don't quite cover the answer I need, so could anyone help a real noob to Java and Mockito? I have code as part of a larger method in a class like so:
private final ExecutorService executorService; //(also declared in constructor)
executorService.submit(() -> {
someCool.stuffInHere
});
And I would like to unit test it with something along the lines of
@Mock
ExecutorService executorServiceMock
doAnswer(invocationOnMock -> {
testSomeCoolStuffInHere;
}).when(executorServiceMock).submit(() -> any())
Is that a correct way to go about it? I'm trying that but I keep getting an error along the lines of:
executorServiceMock.submit(CLassName$$LongLambdaAddress) at ClassName
has following stubbings with different arguments
1. executorServiceMock.submit(CLassName$$ADifferentLongLambdaAddress)
Thanks for looking. hopefully there's enough info there. I'm hoping it's something simple.
You are not submitting () -> any()
. You are submitting a Callable<T>
or a Runnable
(the latter in your case, because you don't return a value).
So if you really want to stub the calls on the executor service (instead of using one of the existing implementations that help with testing, e.g. Runnable::run
is a handy Executor
to use in a test), you must use the correct argument matcher.
Your code is effectively equivalent to:
doAnswer(invocationOnMock -> {
testSomeCoolStuffInHere;
}).when(executorServiceMock).submit(eq(() -> null))
Instead, you want to match a runnable:
doAnswer(invocationOnMock -> {
testSomeCoolStuffInHere;
}).when(executorServiceMock).submit(any(Runnable.class))
(or any<Runnable>()
– this will match null
as well)