繁体   English   中英

如何在Java中模拟单元测试的泛型参数?

[英]How to mock a generic parameter for a unit test in Java?

我有一个函数签名,我想模拟外部服务。

public <T> void save(T item, AnotherClass anotherClassObject);

鉴于此函数签名和类名称IGenericService如何使用PowerMock进行模拟? 还是Mockito?

对于这个泛型,我正在使用:T in T itemT item类的Theodore 例如,我尝试使用:

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); 

分享同样的命运。

尝试使用Mockito的ArgumentMatcher 此外,在when只放了假的参考:

doReturn(null).when(iGenericServiceMock).save(
    ArgumentMatchers.<Theodore>any(), ArgumentMatchers.any(AnotherClass.class));

您将错误的参数传递给when 它可能有点令人困惑,但是when方法有两种不同的用法(实际上是两种不同的方法):

  1.  when(mockedObject.methodYouWantToMock(expectedParameter, orYourMatcher)).thenReturn(objectToReturn); 
  2.  doReturn(objectToReturn).when(mockedObject).methodYouWantToMock(expectedParameter, orYourMatcher); 

注意:在两种情况下都要注意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

伟大而迅速的答案! 我终于通过以下代码顺利完成了:

doNothing().when(iGenericServiceMock).save(Mockito.any(), Mockito.any()); 

直到我将Mockito添加到Intellij再次变得快乐的任何方法之前。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM