With Mockito, how do I verify my lambda expression was called?

Viewed 16777

I am trying to test a method that takes a Consumer function, and I want to verify with Mockito that my lambda expression is called exactly once. What I'm using now is the kind of clunky way of using a flag on a final, single-element array:

final boolean[] handlerExecuted = {false};
instance.conditionalRun(item -> {
  handlerExecuted[0] = true;
  item.foo();
});

Assert.assertTrue(
    "Handler should be executed.",
    handlerExecuted[0]);

It seems like there should be a better way (with a Mockito spy, perhaps) to verify that this lambda expression was called exactly once.

5 Answers

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
    }
Related