問題描述
我有一個 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 可以在方法調用時根據參數的值來驗證參數嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!