我想用Mockito在Junit5中为以下方法编写测试。
public List<Data> getData(Long id) {
UriComponents uriComponents = UriComponentsBuilder.fromUriString("test.com")
.pathSegment("/test")
.queryParam("filters[id]", id)
.build();
Request request = new Request.Builder()
.url(uriComponents.toUriString())
.method("GET", null)
.build();
try {
Response response;
response = okHttpClient.newCall(request).execute();
TypeReference<List<Data>> listType = new TypeReference<>() {};
List<Data> list = objectMapper.readValue(Objects.requireNonNull(response.body()).string(), listType);
response.close();
return list;
} catch (IOException ioEx) {
throw new RuntimeException(ioEx);
}
}
测试
@Test
public void shouldReturnData() throws IOException {
try (MockedStatic<UriComponentsBuilder> mocked = mockStatic(UriComponentsBuilder.class)) {
mocked.when(() -> UriComponentsBuilder.fromUriString("test.go").pathSegment("test")
.queryParam("filters[1]").build()).thenReturn(uriComponents);
TypeReference<List<Data>> listType = new TypeReference<>() {};
List<Data> expectedData = new ObjectMapper().readValue("{}", listType);
List<Data> actualData = MyClient.getData(1234L);
Assertions.assertEquals(expectedData, actualData);
}
}
考试失败了,以下是例外情况:-
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
UriComponents$MockitoMock$2089413864 cannot be returned by fromUriString()
fromUriString() should return UriComponentsBuilder
我无法模仿UriComponentsBuilder,因为这个exception.Can,这里有人能帮我吗?
发布于 2022-01-14 21:13:31
您正在尝试模拟这行中的四个方法调用:
mocked.when(() -> UriComponentsBuilder.fromUriString("test.go").pathSegment("test")
.queryParam("filters[1]").build()).thenReturn(uriComponents);
你不能这么做。一次只能模拟一个方法调用。
如果您想模拟出UriComponentsBuilder
,那么您必须创建一个模拟UriComponentsBuilder
,模拟pathSegment
和queryParam
方法来返回模拟UriComponentsBuilder
实例,最后模拟build()
方法以返回uriComponents
UriComponentsBuilder uriComponentsBuilder = mock(UriComponentsBuilder.class);
mocked.when(() -> UriComponentsBuilder.fromUriString("test.go"))
.thenReturn(uriComponentsBuilder);
when(uriComponentsBuilder.pathSegment("test")).thenReturn(uriComponentsBuilder);
when(uriComponentsBuilder.queryParam("filters[1]")).thenReturn(uriComponentsBuilder);
when(uriComponentsBuilder.build()).thenReturn(uriComponents);
https://stackoverflow.com/questions/70715811
复制相似问题