我在应用程序中使用 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() 但没有成功。
实际的方法调用是:
exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
但是现在当您将第一个参数存根为
NULL
时,编译器不知道它的类型。所以它认为你正在存根具有 4 个参数的方法,即:
exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType)
所以实际的方法调用永远不会被存根,它应该返回 NULL 或
UnnecessaryStubbingException
给我。不知道为什么你会得到 PotentialStubbingProblem
但...
无论如何,尝试更改为以下内容应该可以让您存根
ApiService
将正确调用的实际方法:
when(restTemplate.exchange((String)eq(null), eq(HttpMethod.Post), any(HttpEntity.class), eq(TrackResponse.class))).thenReturn(response);
或者更好:
when(restTemplate.exchange((String)isNull(), eq(HttpMethod.Post), any(HttpEntity.class), eq(TrackResponse.class))).thenReturn(response);