I have the following implementation of class A, using spring boot. A is an abstraction over restTemplate to make GET/POST/PUT RestAPI calls. Tests are written using 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;
}
}
Unit Test With 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));
}
}
My thought behind this implementation is to mock the restTemplate's exchange method, and return a response, upon calling A's perform method. Right now null is being returned upon A's perform method. Looks like I am doing something wrong. Can someone pls assist me on this?
To circumvent this, I mocked the RestTemplate and used
Mockito.verify(restTemplate, Mockito.atMost(1)).exchange(Mockito.any(),Mockito.eq(HttpMethod.POST), Mockito.any(HttpEntity.class), Mockito.eq(String.class));
to find out how many times restTemplate.exchange method has been called. Tests are passing now. But still want to know what's wrong with the implementation posted in the question
Update: On instantiating the restTemplate, the test passed. Did the following change to the test code.
@Spy
RestTemplate restTemplate = new RestTemplate();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.