Mockito单元测试RestTemplate
我正在使用RestTemplate
postForEntity
方法将正文发布到端点。我需要使用Mockito为我的代码编写测试用例的帮助。返回类型为void,但是可以将其更改为,Types
或者code
需要进行测试。我已经提到了许多其他文档,但是它们非常笼统,我尝试使用它们,但是由于request
and和return类型是不同的,所以大多数对我来说都不起作用。。任何建议表示赞赏。谢谢
这是我的Java课
public void postJson(Set<Type> Types){ try {
String oneString = String.join(",", Types);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", oneString);
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
}
}
回答:
您正在测试MyClass类中的逻辑,因此不应模拟它。RestTemplate
是MyClass内部的依赖项,因此这正是您需要模拟的内容。通常,它在测试中应如下所示:
这只是一个简单的例子。一个好的做法是检查传递给您的模拟的参数是否等于期望的参数。一种方法是Mockito.eq()
用实际的预期数据代替。另一个是单独验证它,如下所示:
public ResponseEntity<String> postJson(Set<Type> Types){ try {
String oneString = String.join(",", Types);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", oneString);
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
}
return Types;
您可以按如下方式编写上述方法的测试
@Mock RestTemplate restTemplate;
private Poster poster;
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), getHttpHeaders());
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, request, String.class);
Mockito.verify(restTemplate, Mockito.times(1)).exchange(
Mockito.eq(uri),
Mockito.eq(HttpMethod.POST),
Mockito.eq(request),
Mockito.eq(String.class));
Assert.assertEquals(result, poster.postJson(mockData));
HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add(// whatever you need to add);
return headers;
}
以上是 Mockito单元测试RestTemplate 的全部内容, 来源链接: utcz.com/qa/434807.html