如何断言一个 lambda 是否已被调用

huangapple go评论65阅读模式
英文:

How to assert if a lambda has been called

问题

我目前正在使用 lambda(Consumer 或 Function)作为我的方法的参数。

我想知道断言 lambda 是否已执行的最佳方法是什么。

我找到了2种解决方案,想知道哪种更好,或者是否还有其他方法。

  1. 使用列表,在每次调用 consumer 时添加对象
   List<Object> listCall = new ArrayList<>();
   myObject.myMethod((param) -> listCall.add(param));
   assertThat(listCall).hasSize(wantedNumberCall);

优点:这个方法可行。您可以计算调用的次数。

缺点:感觉有点奇怪,只为了测试这样的情况而添加自定义的 lambda。

  1. 使用 Mockito 来模拟您的 Consumer/Function
   myObject.myMethod(consumerMock);
   Mockito.verify(consumerMock, Mockito.times(0)).apply(any());

优点:Mockito 有很多选项来计算带有参数的调用次数。

缺点:Mockito 不建议模拟您不拥有的对象。有时需要模拟的内容不仅限于 apply(Consumer)或 accept(Consumer)。

英文:

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&lt;Object&gt; listCall = new ArrayList&lt;&gt;()
   myObject.myMethod((param)-&gt;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)

答案1

得分: 1

可能有点过度,但脑海中除了使用StackWalker将断言与lambda完全分离外,没有其他想法。只需断言您的consumerMock位于堆栈中的正确位置。

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

英文:

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

huangapple
  • 本文由 发表于 2020年9月10日 05:39:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63819908.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定