Ruokki
Ruokki

Reputation: 957

How to assert if a lambda has been called

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.

  1. 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

  1. 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)

Upvotes: 1

Views: 1724

Answers (1)

Olivier Samson
Olivier Samson

Reputation: 703

Might be a bit overkill, but nothing comes to mind except of using the StackWalker to completely separate the assert from the lambda. Just assert your consumerMock is where it should be in the stack

https://docs.oracle.com/javase/9/docs/api/java/lang/StackWalker.html

Upvotes: 1

Related Questions