Mockito可以根据方法调用时的值验证参数吗? [英] Can Mockito verify parameters based on their values at the time of method call?

查看:617
本文介绍了Mockito可以根据方法调用时的值验证参数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Foo 类,它是SUT和一个 Bar 类,它是它的协作者。 Foo Bar run(List< Object> values) c>以 expectedList 作为参数。然后, Foo 将向此列表添加更多元素,以使其状态与其处于不同状态调用 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);
}

请注意,协作者实际上是间谍对象而不是模拟对象。此测试用例将失败,因为即使使用等于 expectedList 的参数调用 run(),它也会被修改并且其当前值不再等于 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 中抛出 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可以根据方法调用时的值验证参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆