我在应用程序中使用RestTemplate的exchange()调用外部API。目前,我正在为restTemplate调用编写junit和mockito测试用例,但我遇到了参数不匹配异常。
这是我的代码
@Service
public class ApiService {
@Autowired
private RestTemplate restTemplate;
@Value("{url}")
private String url;
public TrackResponse getTpiValue(TrackRequest trackRequest){
TrackResponse trackResponse = null;
HttpHeaders headers = new HttpHeaders();
HttpEntity<TrackRequest> entity = new HttpEntity<TrackRequest>(trackRequest, headers);
ResponseEntity<TrackResponse> response = restTemplate.exchange(url, HttpMethod.Post, entity, TrackResponse.class);
if(response.getStatusCode == HttpStatus.ok){
trackResponse = response.getBody();
}
return trackResponse;
}
}
这是我的测试案例
@TestInstance(Lifecycle.PER_CLASS)
@ExtendWith(MocikotExtension.class)
public class ApiServiceTest {
@Mock
private RestTemplate restTemplate;
@InjectMocks
private ApiService apiService;
public void getTpiValueTest(){
TrackRequest trackRequest = new TrackRequest();
trackRequest.setId("UTHL10");
TrackResponse trackResponse = new TrackResponse();
trackResponse.setTrackId("QWEDRTHFDS");
ResponseEntity<TrackResponse> response = new ResponseEntity<>(trackResponse, HttpStatus.ok);
when(restTemplate.exchange(eq(null), eq(HttpMethod.Post), any(HttpEntity.class), eq(TrackResponse.class))).thenReturn(response);
TrackResponse finalResponse = apiService.getTpiValue(trackRequest);
assetEquals(response.getbody(), finalResponse.getTrackId());
}
}
但是当我运行测试用例时,我得到的错误低于
org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'exchange' method:
restTemplate.exchange(
null,
POST,
<com.application.track.TrackRequest@3c486eb1,[]>,
class com.application.track.TrackResponse
);
-> at com.application.track.ApiService.getTpiValue(ApiService.java:18)
- has following stubbing(s) with different arguments:
1. restTemplate.exchange(
null,
null,
null,
null
);
-> at com.application.track.ApiServiceTest.getTpiValueTest(ApiServiceTest.java:21)
我也试过使用lenient(),但它不起作用。
1条答案
按热度按时间cgh8pdjw1#
实际的方法调用是:
但是现在,当您将第一个参数stub为
NULL
时,编译器不知道它的类型。因此,它认为你正在创建具有4个参数的方法,即:因此,实际的方法调用永远不会被存根,它应该返回NULL或
UnnecessaryStubbingException
给我。不知道为什么你得到PotentialStubbingProblem
虽然.无论如何,尝试更改以下内容应该可以让您正确地存根
ApiService
将调用的实际方法:或者更好的是: