With Mockito, how do I verify my lambda expression was called?
You can verify that your method was called with any lambda expression was called like this:
verify(someClass).myMethodThatExpectsALambda(any())
private fun <T> any(): T {
Mockito.any<T>()
return null as T
}
Some of the other answers offer alternatives to doing exactly what I want here, but this is doable by Spying the Consumer
class itself and having the spy call the method you really want to execute. A helper method for wrapping the lambda to create the spy helps here:
/** Get a spied version of the given Consumer. */
private Consumer<Item> itemHandlerSpy(Consumer<Item> itemHandler) {
// Create a spy of the Consumer functional interface itself.
@SuppressWarnings("unchecked")
Consumer<Item> spy = (Consumer<Item>) Mockito.spy(Consumer.class);
// Tell the spy to run the given consumer when the Consumer is given something to consume.
Mockito.doAnswer(it -> {
// Get the first (and only) argument passed to the Consumer.
Item item = (Item) it.getArguments()[0];
// Pass it to the real consumer so it gets processed.
itemHandler.accept(item);
return null;
}).when(spy).accept(Mockito.any(Item.class));
return spy;
}
And then the test method becomes very straightforward:
Consumer<Item> itemHandler = itemHandlerSpy(Item::foo);
instance.conditionalRun(itemHandler);
// This verifies conditionalRun called the Consumer exactly once.
Mockito.verify(itemHandler).accept(Mockito.any(Item.class));