如何模拟HTTP客户端后期服务

问题描述 投票:0回答:1

我想模拟以下代码行:

ResponseEntity<String> response = client.callPostService(url, dto, new ParameterizedTypeReference<String>(){});

尝试

@Test
public void testFunction{
    HTTPSClient client = Mockito.mock(HTTPSClient.class);
    Mockito.when(client.callPostService(any(String.class),any(Dto.class), new ParameterizedTypeReference<String>{}))
}

我收到有关我所放置的参数的错误。

http post mocking mockito powermockito
1个回答
1
投票

在配置模拟行为时,不应混合使用Mockito的参数匹配器(如any(),eq()等)和真实对象。

所以,在你的情况下,下一个是正确的:

Mockito.when(client.callPostService(any(String.class),any(Dto.class), Mockito.any(ParameterizedTypeReference.class))).thenReturn(...)

或者(从Java 8开始):

Mockito.when(client.callPostService(any(String.class),any(Dto.class), Mockito.any())).thenReturn(...)

由于增强的类型推断,后者也不会引发关于未经检查的泛型类型转换的编译器警告。

© www.soinside.com 2019 - 2024. All rights reserved.