我有一个函数签名,我想模仿一个外部服务。
public <T> void save(T item, AnotherClass anotherClassObject);
给定此函数签名和类名IGenericService
,如何使用PowerMock来模拟它?还是莫基托?
对于这个泛型,我使用:类Theodore
作为T item
中的T。例如,我尝试使用:
doNothing().when(iGenericServiceMock.save(any(Theodore.class),
any(AnotherClass.class));
IntelliJ曲柄如下:
save(T, AnotherClass) cannot be applied to
(org.Hamcrest.Matcher<Theodore>, org.Hamcrest.Matcher<AnotherClass>)
它列举了以下原因:
reason: No instance(s) of type variable T exist
so that Matcher<T> conforms to AnotherClass
首先,如果泛型参数处理得当,这个问题就应该解决。在这种情况下,你能做些什么呢?
更新: ETO分享如下:
doNothing().when(mockedObject).methodToMock(argMatcher);
同样的命运。
发布于 2018-10-31 12:17:46
您正在向when
传递错误的参数。这可能有点令人困惑,但when
方法有两种不同的用法(实际上是两种不同的方法):
注意:两种情况下都要注意when
方法的输入参数。
在您的特殊情况下,您可以这样做:
doReturn(null).when(iGenericServiceMock).save(any(Theodore.class), any(AnotherClass.class));
这将解决您的编译问题。但是,使用org.mockito.exceptions.misusing.CannotStubVoidMethodWithReturnValue
在运行时测试将失败,因为您试图从void
方法返回某些内容(null
不是void
)。你应该做的是:
doNothing().when(iGenericServiceMock).save(any(Theodore.class), any(AnotherClass.class));
稍后,您可以使用verify
方法检查与模拟的交互。
更新:
检查你的进口品。您应该使用org.mockito.Matchers.any
而不是org.hamcrest.Matchers.any
。
发布于 2018-10-31 11:37:24
尝试使用Mockito的ArgumentMatcher
。在when
中,也只提供了模拟的引用:
doReturn(null).when(iGenericServiceMock).save(
ArgumentMatchers.<Theodore>any(), ArgumentMatchers.any(AnotherClass.class));
发布于 2018-10-31 13:08:39
答案又快又棒!最后,我使用了以下代码来平滑它:
doNothing().when(iGenericServiceMock).save(Mockito.any(), Mockito.any());
直到我使莫基托接受了任何方法后,Intellij才再次对此感到高兴。
https://stackoverflow.com/questions/53082310
复制相似问题