[英]Getting null response of resttemplate exchange in a mockito test
i am trying to write the mock test case for RestServiceImpl class.我正在尝试为 RestServiceImpl class 编写模拟测试用例。 Below is the code.下面是代码。 And i have a test class shown below RestServiceImplTest.我有一个测试 class,如下所示 RestServiceImplTest。 When i run the test class it returning null from line restTemplate.exchange(UrlString, HttpMethod.POST, request, Object.class)当我运行测试 class 它从行 restTemplate.exchange(UrlString, HttpMethod.POST, request, Object.class) 返回 null
public class RestServiceImpl
private RestTemplate restTemplate;
@Autowired
public RestServiceImpl(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@Override
public ResponseEntity<Object> restService(DataRequest dataRequest) throws Exception {
ResponseEntity<Object> response = null;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<DataRequest> request = new HttpEntity<>(dataRequest, headers);
try {
response = restTemplate.exchange(UrlString, HttpMethod.POST, request, Object.class);
} catch (Exception ex) {
throw ex;
}
return response;
}
}
Test class测试 class
@RunWith(SpringRunner.class)
public class RestServiceImplTest {
private RestServiceImpl restServiceImpl;
@Mock
private RestTemplate restTemplate;
@Mock
private DataRequest dataRequest;
@Before
public void setUp() {
restServiceImpl = new RestServiceImpl(restTemplate);
dataRequest = new DataRequest();
}
@Test
public void testRestServiceImplwithSuccess() throws Exception {
ResponseEntity<Object> resp = new ResponseEntity<Object>(HttpStatus.OK);
doReturn(resp).when(restTemplate).exchange(any(URI.class), any(HttpMethod.class), any(HttpEntity.class),
any(Class.class));
ResponseEntity<Object> mockResp = restServiceImpl.restService(DataRequest);
}
Can anybody tell me where is it going wrong.谁能告诉我哪里出错了。
Almost certainly this is happening because your doReturn is not being used due to the parameters not being met (your any() s).几乎可以肯定这种情况正在发生,因为由于未满足参数(您的any() s)而未使用您的doReturn 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.