这是我的类,它有两个方法get和exchange,我不知道如何为下面的两个方法编写测试用例,因为我们使用的是**“new RestTemplate(new HttpComponentsClientHttpRequestFactory()).exchange”**我不知道如何模仿它。
以及如何为同一个类中的另一个方法编写测试用例
@Service
public class TestServiceImpl implements TestService{
@Override
public Object get(String endpoint, ParameterizedTypeReference reference, boolean useToken) {
ResponseEntity response = exchange(HttpMethod.GET, endpoint, null, reference, useToken);
return response.getBody();
}
public ResponseEntity<Object> exchange(HttpMethod httpMethod, String endpoint, @Nullable Object body, ParameterizedTypeReference<Object> reference, boolean useToken,String userId) {
try {
response = new RestTemplate(new HttpComponentsClientHttpRequestFactory()).exchange(endpoint, httpMethod, new HttpEntity<>(body, headers), reference);
return response;
} catch (Exception e) {
e.printStackTrance
}
}
}
}
@Test
public void getTest(){
IdmService idmService1 = Mockito.spy(idmService);
Mockito.doReturn(TestData.getMockResponseEntity()).when(idmService1).exchange(any(),anyString(),any(),any(),anyBoolean());
assertEquals(TestData.getMockResponseEntity().getBody(),idmService.get(endPoint,any(),true));
}
@Test
public void exchangeTest(){
when(restTemplate.exchange(anyString(), ArgumentMatchers.any(HttpMethod.class),ArgumentMatchers.any(HttpEntity.class),
ArgumentMatchers.any(HttpHeaders.class))).thenReturn(TestData.getMockResponseEntity())
assertEquals(TestData.getMockResponseEntity().getBody(),idmService.get(endPoint,any(),true));
}
1条答案
按热度按时间goqiplq21#
当你这样创建
RestTemplate
时,你不能嘲笑它。而是创建一个可以注入的工厂,并模拟该工厂以返回模拟
RestTemplate
:然后在
TestServiceImpl
中:最后在你的测试中