英文:
How to assert if a lambda has been called
问题
我目前正在使用 lambda(Consumer 或 Function)作为我的方法的参数。
我想知道断言 lambda 是否已执行的最佳方法是什么。
我找到了2种解决方案,想知道哪种更好,或者是否还有其他方法。
- 使用列表,在每次调用 consumer 时添加对象
List<Object> listCall = new ArrayList<>();
myObject.myMethod((param) -> listCall.add(param));
assertThat(listCall).hasSize(wantedNumberCall);
优点:这个方法可行。您可以计算调用的次数。
缺点:感觉有点奇怪,只为了测试这样的情况而添加自定义的 lambda。
- 使用 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.
- 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)
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论