Can Mockito verify parameters based on their values at the time of method call?(Mockito 可以在方法调用时根据参数的值来验证参数吗?)
问题描述
我有一个 Foo 类,它是 SUT 和一个 Bar 类,它是它的合作者.Foo 调用 Bar 上的 run(List 并以expectedList"作为参数.然后,Foo 将向这个 List 添加更多元素,使其状态与调用 run()时的状态不同代码>.这是我的测试用例.
I have a Foo class which is SUT and a Bar class, which is its collaborator. Foo calls run(List<Object> values) on the Bar with "expectedList" as an argument. Then, Foo will add a few more elements to this List so that its state will be different from what it was at the time of calling run(). Here's my test case.
@Test
public void testFoo() {
Bar collaborator = spy(new Bar());
Foo sut = new Foo(collaborator);
verify(collaborator).run(expectedList);
}
请注意,协作者实际上是一个间谍对象,而不是一个模拟对象.这个测试用例将失败,因为即使 run() 是使用等于 expectedList 的参数调用的,但它已被修改,因为它的当前值不再等于 expectedList代码>.但是,这是它应该工作的方式,所以我想知道是否有办法让 Mockito 在调用方法时存储参数的快照,并根据这些值而不是最近的值来验证它们.
Note that the collaborator is actually a spy object rather than a mock. This test case will fail because even though run() was called with an argument equal to expectedList, it was modified since and its current value no longer equals expectedList. However, this is the way it is supposed to work, so I'm wondering if there's a way to have Mockito store the snapshot of parameters when a method is called and verify them based on these values rather than the most recent values.
推荐答案
在调用方法时使用 Answer 检查参数的值.如果值错误,您可以在 Answer 中抛出 AssertionError,或者您可以存储该值,并在最后进行断言.
Use an Answer to check the value of the argument when the method is called. You can either throw an AssertionError within the Answer if the value is wrong, or you can store the value, and do your assertion at the end.
这篇关于Mockito 可以在方法调用时根据参数的值来验证参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mockito 可以在方法调用时根据参数的值来验证参数吗?
基础教程推荐
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
