如何在单元测试中模拟REST API?
我正在使用RestTemplate exchange
HttpMethod.POST方法发布到端点。在我的测试文件中,我正在测试success
POST方法。但是用我目前的测试,我得到了401
Unauthorized errorPOST请求。在测试文件中发出POST请求时,我需要模拟API的帮助
这是我的主文件
@Componentpublic class DataTestRepo {
private final RestTemplate restTemplate;
private final String url;
private final AllBuilder headersBuilder;
public DataTestRepo(
@Qualifier(Oauth.BEAN_NAME) AllBuilder headersBuilder,
RestTemplate restTemplate, String url) {
this.headersBuilder = headersBuilder;
this.restTemplate = restTemplate;
this.url = url;
}
public ResponseEntity<String> postJson(Set<String> results) {
ResponseEntity<String> result = null;
try {
JSONObject jsonObject = new JSONObject(body);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
restTemplate.getMessageConverters().add(stringConvertor);
result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
return result;
}
}
这是我的测试文件
@RunWith(MockitoJUnitRunner.class)@TestPropertySource
public class DataTestRepoTest {
private static final String url = "http://localhost:8080/data/name";
@Mock
private DataTestRepo DataTestRepo;
RestTemplate restTemplate = new RestTemplate();
@Test
public void restTemplateHttpPost_success() throws URISyntaxException {
URI uri = new URI(url);
Set<String> mockData = Stream.of("A","B").collect(Collectors.toSet());
Map<String, String> body = new HashMap<>();
body.put("Name", "Aws");
JSONObject jsonObject = new JSONObject(body);
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST,
new HttpEntity<>(request, DataTestRepo.getHttpHeaders()), String.class);
Assert.assertEquals(201, result.getStatusCodeValue());
}
}
回答:
您正在测试DataTestRepo类内部的逻辑,因此您不应模拟它。RestTemplate是DataTestRepo内部的一个依赖项,因此这正是您需要模拟的。通常,它在测试中应如下所示:
@InjectMocksprivate DataTestRepo DataTestRepo;
@Mock
RestTemplate restTemplate;
同样,您将必须为模拟的依赖项提供一个返回值,如下所示:
Mockito.when(restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any())).thenReturn(new ResponseEntity<>(yourExpectedDataHere, HttpStatus.OK));enter code here
这只是一个简单的例子。一个好的做法是检查传递给您的模拟的参数是否等于期望的参数。一种方法是将ArgumentMatchers.any()替换为实际的预期数据。另一个是单独验证它,如下所示:
Mockito.verify(restTemplate, Mockito.times(1)).exchange(ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere), ArgumentsMatchers.eq(yourExpectedDataHere));
以上是 如何在单元测试中模拟REST API? 的全部内容, 来源链接: utcz.com/qa/402555.html