1

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)

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Ruokki
  • 869
  • 1
  • 7
  • 24
  • What test framework are you using? – gagarwa Sep 09 '20 at 21:46
  • Junit 5 with assertj and mockito – Ruokki Sep 09 '20 at 21:47
  • Just so I have this right, `myMethod` takes in a lambda expression, and you want to check if that lambda expression has executed? – gagarwa Sep 09 '20 at 21:59
  • I would just say to check the *effect* of the lambda, in the example you provided, the size of the `listCall`. You only need to test something like if a lambda executed is if it is part of an API/library. – gagarwa Sep 09 '20 at 22:06
  • Mockito seems a natural choice to verify interactions. – Joel Costigliola Sep 10 '20 at 21:16
  • Yes natural but in fact i'm not the garant of how Consumer/Function work ? So if i misunderstood one of the method for example andThen my test will be wrong (even if he pass) – Ruokki Sep 11 '20 at 06:36

1 Answers1

1

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

Olivier Samson
  • 609
  • 4
  • 13
  • 1
    Yes, I think this is a bit overkill. Tests should be as simple as possible. But, +1, as I didn't know about `StackWalker` before. – gagarwa Sep 10 '20 at 14:56