I'm currently working with lambda (Consumer or Function) as a parameter of my methods.
And I'm wondering what is the best way to assert if the lambda has been executed.
I've found 2 solution and I wonder which one is the better or if something else exists.
- Use a list and add Object each time the consumer is called
List<Object> listCall = new ArrayList<>()
myObject.myMethod((param)->listCall.add(param))
asserThat(listCall).hasSize(wantedNumberCall)
Pro: This is working. You can count the number of call
Cons: Feel a little awkward to add this custom lambda just for testing something like that
- Use Mockito to mock your Consumer/Function
myObject.myMethod(consumerMock)
Mockito.verify(consumerMock,Mockito.times(0)).apply(any());
Pro: Mockito have a lot of option to count call with argument.
Cons: Mockito doesn't recommend to mock objects you don't own. And it need to mock sometimes more than just apply(Consumer) or accept (Consumer)