我有一个服务我嘲笑这样:
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
@InjectMocks
MyService myService;
@Test
void testSendRec() {
myService.sendDocRec(.. pass params..);
}
}
该服务:
@Service
public class MyService {
String sendDocRec( params ) {
// builds request
HttpUriRequestBase request = getRequest( params );
String response = doRequest(request);
}
public String doRequest(ClassicHttpRequest request) {
String result = null;
try (CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(this.connectionManager)
.setConnectionManagerShared(true)
.setDefaultRequestConfig(this.requestConfig)
.build()) {
final HttpClientContext clientContext = HttpClientContext.create();
try (CloseableHttpResponse response = httpclient.execute(request, clientContext)) {
result = EntityUtils.toString(response.getEntity());
}
} catch (URISyntaxException e) {
log.error("Invalid URI {}", e);
} catch (IOException e) {
log.error("Failed to make HTTP Request {}", e);
} catch (ParseException e) {
log.error("Failed parsing response body {}", e);
}
return result;
}
}
我需要能够模拟“ClosebleHttpResponse response = httpclient.execute(request,clientContext)",这样“response”对象是我提前创建的。我希望一些模拟的when/then结构能起作用?我会很感激关于如何做到这一点的想法。谢谢!
1条答案
按热度按时间8ehkhllq1#
你不能用当前的代码结构来做。httpclient对象是在测试的方法中创建的。所以它不能被模仿。
您需要将httpclient对象的创建委托给另一个方法,该方法属于不同的类(类似于HttpClientFactory类)。该HttpClientFactory类应仅负责创建httpClient示例。如果需要,您可以为该类编写单独的单元测试用例。
现在你可以像下面这样嘲弄回应: