gpt4 book ai didi

java - 如何在 Java 中模拟单元测试的通用参数?

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:00:49 28 4
gpt4 key购买 nike

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

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

给定此函数签名和类名 IGenericService 如何使用 PowerMock 模拟它?还是莫基托?

对于这个泛型,我使用的是: T item 中的 T 类 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); 

命运相同。

最佳答案

您向 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 方法检查与您的 mock 的交互。

更新:

检查您的导入。您应该使用 org.mockito.Matchers.any 而不是 org.hamcrest.Matchers.any

关于java - 如何在 Java 中模拟单元测试的通用参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53082310/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com