问题描述
我正在使用RestTemplate postForEntity
方法将正文发布到端点.我需要使用Mockito为我的代码编写测试用例的帮助.返回类型为void,但是如果需要测试,可以将其更改为Types
或code
.我提到了许多其他文档,但是它们非常笼统,我尝试使用它们,但是大多数request
和return类型对我来说都不起作用. .任何建议表示赞赏.谢谢
I am using RestTemplate postForEntity
method to post body to an endpoint. I need help with writing test case for my code using Mockito. The return type is void but it can be changed to Types
or code
if needed to test. I have referred many other documentation but they are very general, I tried using them but most did not work for me as the request
and return type are different. . Any suggestions are appreciated. Thank you
这是我的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内部的依赖项,因此这正是您需要模拟的.通常,它在您的测试中应如下所示:
You are testing the logic inside MyClass class, so you should not mock it. RestTemplate
is a dependency inside MyClass, so this is exactly what you need to mock. In general it should look like this inside your test:
这只是一个简单的例子.一个好的做法是检查传递给您的模拟的参数是否等于期望的参数.一种方法是用实际的预期数据替换Mockito.eq()
.另一个是单独验证它,就像这样:
This is just a simple example. A good practice would be to check that the arguments passed to your mock equal to the expected ones. One way would be to replace Mockito.eq()
with the real expected data. Another is to verify it separately, like this:
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;
您可以按以下步骤编写上述方法的测试
You can write test for above method as follows
@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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!