gpt4 book ai didi

java - 将泛型与 Mockito 匹配

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:45:35 28 4
gpt4 key购买 nike

我正在尝试模拟 Spring Rest 的 restTemplate.exchange 方法。

在同一测试中,我有多个调用,仅返回类型不同。

这是我创建的模拟方法

首先

// Original method
restTemplate.exchange(UrlMap.SEARCH + '?' + searchDocsForm.toQueryParams(),
HttpMethod.GET, null, new ParameterizedTypeReference<SearchResultsDTO<SolrDocumentDTO>>() {
})
// Mock
when(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(), Matchers.<ParameterizedTypeReference<SearchResultsDTO<SolrDocumentDTO>>>any())).thenReturn(
new ResponseEntity<>(searchResultsDTO, HttpStatus.OK));

第二

// Original method
restTemplate.exchange(UrlMap.ALL_DOCUS_TOPICS,
HttpMethod.GET, null, new ParameterizedTypeReference<List<SelectItem>>() {
}).getBody();
// Mock
when(restTemplate.exchange(any(String.class), any(HttpMethod.class), any(), Matchers.<ParameterizedTypeReference<List<SelectItem>>>any())).thenReturn(
new ResponseEntity<>(selectItems, HttpStatus.OK));

mock 不考虑 ParameterizedTypeReference 的通用参数,最后定义的 mock 胜过前者。

有什么办法可以让它发挥作用吗?

最佳答案

Mockito 本身并不擅长匹配泛型,但您的解决方案比一般情况要简单得多。

替换你的:

Matchers.<ParameterizedTypeReference<SearchResultsDTO<SolrDocumentDTO>>>any())

与:

eq(new ParameterizedTypeReference<SearchResultsDTO<SolrDocumentDTO>>() {}))

首先,Matchers.any()不匹配类型,甚至在其 any(Foo.class) 中也不匹配多样性(从 Mockito 1.x 开始)。 any()火柴all values, including null and including incorrect types :

Matches any object, including nulls

This method doesn't do type checks with the given parameter, it is only there to avoid casting in your code. This might however change (type checks could be added) in a future major release.

(“ future 主要版本”可能会在 Mockito 2 中实现,其中可能会引入 isA 样式的类型检查。;参见 commentary from Mockito committer Brice。)

泛型有助于为 exchange 获取正确的参数和 thenReturn , 但因为 type erasure这些类型信息都没有进入 CLASS 文件,更不用说 JVM 了。唯一断言其参数类型的匹配器是 isA ,它采用类文字并且不会帮助您进行参数化类型。

您可以编写一个自定义匹配器来检查参数的类型和类型参数(如果它们不受删除影响),但对于您的特定情况,这不是必需的。

类型删除是全部原因ParameterizedTypeReference存在:它将泛型信息捕获到子类中,其中参数化类型不会被删除。同样的模式用于 TypeToken在 Guava 或TypeLiteral在吉斯。所有这些实现都将参数化类型描述为实例

重要的是,所有这些——包括 ParameterizedTypeReference —支持equalshashCode , 所以 new ParameterizedTypeReference<A<B>>(){}等于 new ParameterizedTypeReference<A<B>>(){}即使实例不同。 (See the code here.)

因为对相同参数化类型的引用是相等的,所以使用 Mockito 的 eq具有不同引用的匹配器,一切都应该没问题。

关于java - 将泛型与 Mockito 匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29670463/

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