Den*_*s C 30 java junit spring unit-testing resttemplate
我有一个直接依赖于RestTemplate的类.我希望我有离线的JUnit测试.
我怎么能在我的单元测试中模拟RestTemplate?
Rae*_*ald 35
Sping 3.0推出RestTemplate.从版本3.2开始,Spring MVC测试框架MockRestServiceServer为单元测试客户端REST代码提供了类.
ska*_*man 31
我建议重构你的客户端代码以删除直接依赖RestTemplate,并将其替换为引用RestOperations,这是由实现的接口RestTemplate.以及你应该编码的那个.
然后,您可以RestOperations在代码中注入存根或模拟以进行单元测试,并RestTemplate在实际使用时注入.
您可以在包中使用Mock类org.springframework.mock.web.
通常你需要MockHttpServletRequest和MockHttpServletResponse,但如果你需要更多的控制,你可能还需要其他人,例如MockRequestDispatcher.
这两者都实现了相应的Servlet接口,但是为测试添加了便利方法(最重要的是:它们在没有真正的HTTP连接的情况下工作).
您可以在弹簧测试罐中找到模拟类(可通过Maven访问)
更新:看来上面的课程RestTemplate毕竟没什么大不了的.你需要的是创建一个模拟器ClientHttpRequestFactory,我很惊讶地看到上面的包中没有一个.这里有一些代码可以帮助您入门(尚未测试过):
public class MockClientHttpRequestFactory implements
ClientHttpRequestFactory{
// overwrite this if you want
protected MockClientHttpResponse createResponse(){
return new MockClientHttpResponse();
}
// or this
protected HttpStatus getHttpStatusCode(){
return HttpStatus.OK;
}
// or even this
@Override
public ClientHttpRequest createRequest(final URI uri,
final HttpMethod httpMethod) throws IOException{
return new MockClientHttpRequest(uri, httpMethod);
}
public class MockClientHttpResponse implements ClientHttpResponse{
private final byte[] data = new byte[10000];
private final InputStream body = new ByteArrayInputStream(data);
private final HttpHeaders headers = new HttpHeaders();
private HttpStatus status;
@Override
public InputStream getBody() throws IOException{
return body;
}
@Override
public HttpHeaders getHeaders(){
return headers;
}
@Override
public HttpStatus getStatusCode() throws IOException{
return getHttpStatusCode();
}
@Override
public String getStatusText() throws IOException{
return status.name();
}
@Override
public void close(){
try{
body.close();
} catch(final IOException e){
throw new IllegalStateException(e);
}
}
}
class MockClientHttpRequest implements ClientHttpRequest{
private final HttpHeaders headers = new HttpHeaders();
private final HttpMethod method;
private final URI uri;
private final OutputStream body = new ByteArrayOutputStream();
MockClientHttpRequest(final URI uri, final HttpMethod httpMethod){
this.uri = uri;
method = httpMethod;
}
@Override
public OutputStream getBody() throws IOException{
return body;
}
@Override
public HttpHeaders getHeaders(){
return headers;
}
@Override
public HttpMethod getMethod(){
return method;
}
@Override
public URI getURI(){
return uri;
}
@Override
public ClientHttpResponse execute() throws IOException{
return createResponse();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24955 次 |
| 最近记录: |