問題描述
我正在測試一些依賴于 RestTemplate
類中的 getForObject()
方法的方法.
I am testing some methods that rely on the getForObject()
method in the RestTemplate
class.
getForObject()
方法重載了簽名getForObject(String url, Class
和 getForObject(字符串 url, 類
The getForObject()
method is overloaded with the signaturesgetForObject(String url, Class<T> responseType, Object... uriVariables)
and getForObject(String url, Class<T> responseType, Map<String, ?>
我需要在其參數中使用 Object...
存根方法以引發異常,但我不能因為 Mockito.any()
還包含 地圖
類型.因此,將方法存根為 getForObject(Mockito.anyString(),Mockito.any(), Mockito.any()
將指向觸發編譯錯誤的兩個方法.
I need to stub the method with Object...
in its arguments to throw an exception but I can not because Mockito.any()
also encompasses the Map
type.
Therefore, stubbing the method as getForObject(Mockito.anyString(),Mockito.any(), Mockito.any()
will point to BOTH methods triggering a compilation error.
這個問題有什么可能的解決方法嗎?
Are there any possible workarounds to this problem?
我已經嘗試使用 Mockito.anyObject()
無濟于事
I have already tried using Mockito.anyObject()
to no avail
推薦答案
不確定你的問題可能是什么,但在這一點上,我不妨發布一個工作示例.
Not sure what your problem might be, but at this point I might as well just post a working example.
如前所述,您需要正確指定每個參數的類型,以便 mockito 可以定位到匹配的方法簽名.
As mentioned before you need to properly specify the type of each parameter, so that mockito can locate the matching method signature.
有關處理舊 mockito 版本使用的可變參數的語法,請查看 這個答案
.
For the syntax to handle varargs used by older mockito versions, check this answer
.
import static org.mockito.ArgumentMatchers.any;
...
@RunWith(MockitoJUnitRunner.class)
public class MockitoTest {
@Test
public void test() throws Exception {
RestTemplate api = Mockito.mock(RestTemplate.class);
Object obj1 = new Object();
Object obj2 = new Object();
Object obj3 = new Object();
Mockito.when(api.getForObject(any(String.class),any(Class.class), ArgumentMatchers.<Object>any())).thenReturn(obj1);
Mockito.when(api.getForObject(any(String.class),any(Class.class), any(Map.class))).thenReturn(obj2);
Mockito.when(api.getForObject(any(URI.class),any(Class.class))).thenReturn(obj3);
Assert.assertEquals(obj1, api.getForObject("", String.class));
Assert.assertEquals(obj1, api.getForObject("", String.class, obj1));
Assert.assertEquals(obj1, api.getForObject("", String.class, obj1, obj2));
Assert.assertEquals(obj1, api.getForObject("", String.class, obj1, obj2, obj3));
Assert.assertEquals(obj1, api.getForObject("", String.class, new Object[] {obj1,obj2,obj3}));
Assert.assertEquals(obj2, api.getForObject("", String.class, new HashMap()));
Assert.assertEquals(obj3, api.getForObject(new URI(""), String.class));
}
}
對于您的用例,只需將 thenReturn
替換為 thenThrow
.
For your usecase just replace the thenReturn
with thenThrow
.
這篇關于用 Mockito 模擬重載的方法的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!