Java 如何模拟rest模板交换
我有一个方法,它使用Java 如何模拟rest模板交换,java,rest,http,Java,Rest,Http,我有一个方法,它使用restemplate。我使用以下代码拨打电话: final ResponseEntity<RESTResponse> responseEntity = restTemplate.exchange(uri, HttpMethod.POST,
restemplate
。我使用以下代码拨打电话:
final ResponseEntity<RESTResponse> responseEntity = restTemplate.exchange(uri,
HttpMethod.POST,
httpEntityWithHeaders,
RESTResponse.class);
但是当运行测试时,它不会抛出异常,它只是继续
有什么建议吗?正如您所说的
httpEntityWithHeads
属于HttpEntity
类型,因此您必须采用与HttpEntity
匹配的存根方式
when(restemplate.exchange(
ArgumentMatchers.contains(随机主机),
ArgumentMatchers.eq(HttpMethod.POST),
ArgumentMatchers.any(),
ArgumentMatchers.any())
).Thenthow(新的ResourceAccessException(“随机异常消息”);
在我看来,您的最后一个参数不是列表,而是一个类,这就是存根失败的原因,我尝试了以下方法,它正在工作
@Test(expected = IllegalArgumentException.class)
public void test() {
RestTemplate restTemplate = mock(RestTemplate.class);
when(restTemplate.exchange(anyString(), ArgumentMatchers.eq(HttpMethod.POST),
any(HttpEntity.class),
any(Class.class))).thenThrow(new IllegalArgumentException("a"));
Rest rest = new Rest(restTemplate);
rest.call();
}
public void call(){
HttpEntity<Object> httpEntityWithHeaders= new HttpEntity<>(null);
final ResponseEntity<Object> responseEntity = restTemplate.exchange("a",
HttpMethod.POST,
httpEntityWithHeaders,
Object.class);
}
@Test(预期=IllegalArgumentException.class)
公开无效测试(){
RestTemplate RestTemplate=mock(RestTemplate.class);
当(restemplate.exchange(anyString()、ArgumentMatchers.eq(HttpMethod.POST)),
任何(HttpEntity.class),
任何(Class.Class))。然后抛出(新的IllegalArgumentException(“a”);
Rest Rest=新Rest(restTemplate);
rest.call();
}
公开作废通知(){
HttpEntity httpEntityWithHeaders=新的HttpEntity(null);
final ResponseEntity ResponseEntity=restTemplate.exchange(“a”,
HttpMethod.POST,
HttpEntityWithHeader,
对象(类);
}
这是否回答了您的问题?
when(restTemplate.exchange(
ArgumentMatchers.contains(randomHost),
ArgumentMatchers.eq(HttpMethod.POST),
ArgumentMatchers.<HttpEntity<String>>any(),
ArgumentMatchers.<ParameterizedTypeReference<List<RESTResponse>>>any())
).thenThrow(new ResourceAccessException("Random exception message."));
@Test(expected = IllegalArgumentException.class)
public void test() {
RestTemplate restTemplate = mock(RestTemplate.class);
when(restTemplate.exchange(anyString(), ArgumentMatchers.eq(HttpMethod.POST),
any(HttpEntity.class),
any(Class.class))).thenThrow(new IllegalArgumentException("a"));
Rest rest = new Rest(restTemplate);
rest.call();
}
public void call(){
HttpEntity<Object> httpEntityWithHeaders= new HttpEntity<>(null);
final ResponseEntity<Object> responseEntity = restTemplate.exchange("a",
HttpMethod.POST,
httpEntityWithHeaders,
Object.class);
}