問題描述
我有一個(gè) Foo
類,它是 SUT 和一個(gè) Bar
類,它是它的合作者.Foo
調(diào)用 Bar
上的 run(List
并以expectedList
"作為參數(shù).然后,Foo
將向這個(gè) List
添加更多元素,使其狀態(tài)與調(diào)用 run()時(shí)的狀態(tài)不同代碼>.這是我的測(cè)試用例.
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);
}
請(qǐng)注意,協(xié)作者實(shí)際上是一個(gè)間諜對(duì)象,而不是一個(gè)模擬對(duì)象.這個(gè)測(cè)試用例將失敗,因?yàn)榧词?run()
是使用等于 expectedList
的參數(shù)調(diào)用的,但它已被修改,因?yàn)樗漠?dāng)前值不再等于 expectedList代碼>.但是,這是它應(yīng)該工作的方式,所以我想知道是否有辦法讓 Mockito 在調(diào)用方法時(shí)存儲(chǔ)參數(shù)的快照,并根據(jù)這些值而不是最近的值來驗(yàn)證它們.
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.
推薦答案
在調(diào)用方法時(shí)使用 Answer
檢查參數(shù)的值.如果值錯(cuò)誤,您可以在 Answer
中拋出 AssertionError
,或者您可以存儲(chǔ)該值,并在最后進(jìn)行斷言.
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.
這篇關(guān)于Mockito 可以在方法調(diào)用時(shí)根據(jù)參數(shù)的值來驗(yàn)證參數(shù)嗎?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!