[英]Error while mocking OkHttpClient with Mockito
I want to write test for the below method in Junit5 with Mockito.我想用 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测试
@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);
}
}
The test is failing with below exception:-测试失败,但有以下异常:-
org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
UriComponents$MockitoMock$2089413864 cannot be returned by fromUriString()
fromUriString() should return UriComponentsBuilder
I am unable to mock UriComponentsBuilder because of this exception.Can anyone please help here?由于这个异常,我无法模拟 UriComponentsBuilder。有人可以在这里帮忙吗?
You are attempting to mock four method calls in this line:您正在尝试在此行中模拟四个方法调用:
mocked.when(() -> UriComponentsBuilder.fromUriString("test.go").pathSegment("test")
.queryParam("filters[1]").build()).thenReturn(uriComponents);
You can't do this.你不能这样做。 You can only mock one method call at a time.
您一次只能模拟一个方法调用。
If you want to mock out UriComponentsBuilder
, then you will have to create a mock UriComponentsBuilder
, mock the pathSegment
and queryParam
methods to return the mock UriComponentsBuilder
instance, and finally mock the build()
method to return 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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.