Mockito 可以在方法调用时根据参数的值来验证参数吗?

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

问题描述

限时送ChatGPT账号..

我有一个 Foo 类,它是 SUT 和一个 Bar 类,它是它的合作者.Foo 调用 Bar 上的 run(List values) 并以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 可以在方法调用时根据参数的值来验证参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!