【问题标题】:Java Mockito with RestTemplate.exchange using GenericsJava Mockito 与 RestTemplate.exchange 使用泛型
【发布时间】:2023-03-31 19:33:01
【问题描述】:

我有一个通用方法,它使用RestTemplate.exchange 调用指定的 URL。方法本身可以正常工作并加载数据,但我无法使用 Mockito 对其进行单元测试。

主要方法

@Service
public class MyClass{
    private <T> List<T> loadData(String url) {
        return restTemplate.exchange(
            url, GET, null, new ParameterizedTypeReference<List<T>>(){}
        ).getBody().stream().collect(toList()));
    }
}

单元测试

@Runwith(MockitoJUnitRunner.class)
public class MyTest {
    @Mock
    private RestTemplate restTemplate;

    @Test
    public void givenCall_myMethod_WillReturnData(){
        given(restTemplate.exchange(
            ArgumentMatchers.anyString(), ArgumentMatchers.any(), any(), any(Class.class)
        ))
        .willReturn(bodyData());
    }
}

如果我使用非泛型版本,那么一切正常,但是 mockito 使用泛型版本返回 NullPointerException

出了什么问题或遗漏了什么?

【问题讨论】:

  • 异常的堆栈跟踪是什么? “如果我使用非通用版本”向我们展示
  • 另外你的类只有一个私有方法,你的测试没有测试任何东西。看起来您删除了太多细节,以至于这不再有意义。
  • 感谢您的时间@Michael。这个网站在我的公司里只有只读模式,所以我一直在尝试在手机上输入所有内容,因此无法提供太多细节:)
  • RestOperations 存在是有原因的。

标签: java spring unit-testing junit mockito


【解决方案1】:

您定义的最后一个通配符为:any(Class.class)

交换方法有签名:

exchange(String url,
             HttpMethod method,
             HttpEntity<?> requestEntity,
             ParameterizedTypeReference<T> responseType) throws RestClientException

您应该将其定义为:any(ParameterizedTypeReference.class)

我还建议将非常模糊的 any() set-us 替换为 any(Class) 等效项。

【讨论】:

  • 谢谢@Maciej。你是对的,我应该使用:any(ParameterizedTypeReference.class)。而不是 Class.class.
猜你喜欢
  • 2015-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2011-09-04
  • 2019-04-10
相关资源
最近更新 更多