用Mockito模拟重载的方法

编程入门 行业动态 更新时间:2024-10-27 18:19:24
本文介绍了用Mockito模拟重载的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在测试某些依赖RestTemplate类中getForObject()方法的方法.

I am testing some methods that rely on the getForObject() method in the RestTemplate class.

getForObject()方法的签名getForObject(String url, Class<T> responseType, Object... uriVariables)和getForObject(String url, Class<T> responseType, Map<String, ?>

我需要在其参数中加Object...的方法存根以引发异常,但我不能这样做,因为Mockito.any()也包含Map类型. 因此,将方法存根为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.

如前所述,您需要正确指定每个参数的类型,以便模仿器可以找到匹配的方法签名.

As mentioned before you need to properly specify the type of each parameter, so that mockito can locate the matching method signature.

有关处理旧版Mockito版本使用的varargs的语法,请检查 .

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模拟重载的方法

本文发布于:2023-10-31 07:07:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545381.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Mockito

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!