问题描述
在测试RestClient-Implementation时,我想模拟一个RestClientException,它可能被该实现f.e中的一些RestTemplate方法抛出。删除方法:
While testing a RestClient-Implementation I want to simulate a RestClientException that may be thrown by some RestTemplate-methods in that implementation f.e. the delete-method:
@Override
public ResponseEntity<MyResponseModel> documentDelete(String id) {
template.setErrorHandler(new MyResponseErrorHandler());
ResponseEntity<MyResponseModel> response = null;
try {
String url = baseUrl + "/document/id/{id}";
response = template.exchange(url, DELETE, null, MyResponseModel.class, id);
} catch (RestClientException ex) {
return handleException(ex);
}
return response;
}
我如何实现这一目标?
我用这种方式定义模拟服务器:
I define the mock-server in this way:
@Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(template);
client = new MyRestClient(template, serverUrl + ":" + serverPort);
}
推荐答案
你可以利用用于模拟来自mockRestServiceServer的4xx或5xx响应。
You can take advantage of the MockRestResponseCreators for mocking 4xx or 5xx responses from the mockRestServiceServer.
例如测试5xx - 内部服务器错误:
For example for testing a 5xx - Internal server error:
mockServer.expect(requestTo("your.url"))
.andExpect(method(HttpMethod.GET/POST....))
.andRespond(withServerError()...);
在您的情况下,针对客户端HTTP错误抛出RestClientException,因此
示例以上可以通过使用以下方式微调 4xx
例外:
... andRespond(withBadRequest());
或 ... andRespond(withStatus(HttpStatus.NOT_FOUND));
In your case the RestClientException is thrown for client-side HTTP errors, sothe example above can be fine tuned for a 4xx
exception by using:...andRespond(withBadRequest());
or ...andRespond(withStatus(HttpStatus.NOT_FOUND));
更简单的用法这些方法使用静态导入 org.springframework.test.web.client.MockRestServiceServer
, org.springframework.test.web.client.response。 MockRestResponseCreators
For a more simpler usage of these methods you use static imports for org.springframework.test.web.client.MockRestServiceServer
,org.springframework.test.web.client.response.MockRestResponseCreators
这篇关于如何使用MockRestServiceServer测试RestClientException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!