本文介紹了如何正確匹配 Mockito 中的可變參數的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我一直在嘗試使用 Mockito 模擬具有可變參數參數的方法:
I've been trying to get to mock a method with vararg parameters using Mockito:
interface A {
B b(int x, int y, C... c);
}
A a = mock(A.class);
B b = mock(B.class);
when(a.b(anyInt(), anyInt(), any(C[].class))).thenReturn(b);
assertEquals(b, a.b(1, 2));
這不起作用,但是如果我這樣做:
This doesn't work, however if I do this instead:
when(a.b(anyInt(), anyInt())).thenReturn(b);
assertEquals(b, a.b(1, 2));
這可行,盡管我在存根方法時完全省略了可變參數參數.
This works, despite that I have completely omitted the varargs argument when stubbing the method.
有什么線索嗎?
推薦答案
Mockito 1.8.1 引入 anyVararg() 匹配器:
Mockito 1.8.1 introduced anyVararg() matcher:
when(a.b(anyInt(), anyInt(), Matchers.<String>anyVararg())).thenReturn(b);
另請參閱歷史記錄:https://code.google.com/存檔/p/mockito/issues/62
編輯棄用后的新語法:
when(a.b(anyInt(), anyInt(), ArgumentMatchers.<String>any())).thenReturn(b);
這篇關于如何正確匹配 Mockito 中的可變參數的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!