我有下面的A类实现,使用spring引导。A是对restTemplate进行GET/POST/PUT RestAPI调用的抽象。测试是用Mockito编写的。
Class A {
@Bean
RestTemplate restTemplate;
public class A(RestTemplate restTemplate){
this.restTemplate = restTemplate;
}
public ResponseEntity perform(String endPoint, String requestBody, String auth, HttpMethod httpMethod){
...code to create parameters to pass to the exchange method
ResponseEntity responseEntity = restTemplate.exchange(url, httpMethod, requestEntity, String.class)
return responseEntity;
}
}用Mockito:单元测试:
class ATest{
A a;
@Spy
RestTemplate restTemplate;
@Before
public void setUp() {
a = Mockito.spy(new A(restTemplate));
}
@Test
public void testHttpUtil(){
ResponseEntity responseEntity = new ResponseEntity(HttpStatus.OK);
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization" , "testAuth");
HttpEntity<String> requestEntity = new HttpEntity<String>("testPayload", headers);
Mockito.doReturn(responseEntity).when(restTemplate).exchange(Mockito.any(),Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(String.class));
ResponseEntity responseEntity1 = a.perform("https://example.com/v1/testapi", "testpayload", "testauthinfo", MediaType.APPLICATION_JSON_VALUE, HttpMethod.POST );
Assert.assertNotNull(responseEntity1);
Mockito.verify(restTemplate, Mockito.atMost(1)).exchange(Mockito.any(),Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(String.class));
}
}这个实现背后的想法是,在调用A的执行方法时,模拟restTemplate的exchange方法,并返回一个响应。现在,在A的执行方法上返回null。看来我做错什么了。有人能帮我吗?
为了规避这个问题,我嘲笑了RestTemplate并使用了
Mockito.verify(restTemplate, Mockito.atMost(1)).exchange(Mockito.any(),Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(String.class));来查找调用restTemplate.exchange方法的次数。测试已经通过了。但仍然想知道问题中发布的实现有什么问题
发布于 2020-12-17 04:56:36
更新:在实例化restTemplate时,测试通过了。对测试代码进行以下更改。
@Spy
RestTemplate restTemplate = new RestTemplate();https://stackoverflow.com/questions/65327875
复制相似问题