用于测试的 Square 改造服务器模拟 [英] Square retrofit server mock for testing
问题描述
在使用 square 改造框架时模拟服务器进行测试的最佳方法是什么.>
可能的方法:
创建一个新的改造 client 并在 RestAdapter.Builder().setClient() 中设置它.这涉及解析 Request 对象并将 json 作为 Response 对象返回.
将此带注释的接口实现为模拟类,并使用它代替 RestAdapter.create() 提供的版本(不会测试 gson 序列化)
?
理想情况下,我希望模拟服务器提供 json 响应,以便我可以同时测试 gson 序列化.
任何示例将不胜感激.
我决定尝试方法一如下
public class MockClient 实现 Client {@覆盖公共响应执行(请求请求)抛出 IOException {Uri uri = Uri.parse(request.getUrl());Log.d("模拟服务器", "获取 uri:" + uri.toString());字符串 responseString = "";if(uri.getPath().equals("/path/of/interest")) {responseString = "此处为 JSON 字符串";} 别的 {responseString = "其他 JSON 响应字符串";}return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", responseString.getBytes()));}}
并通过以下方式使用它:
RestAdapter.Builder builder = new RestAdapter.Builder();builder.setClient(new MockClient());
它运行良好,让您无需联系真实服务器即可测试您的 json 字符串!
What's the best way to mock a server for testing when using the square retrofit framework.
Potential ways:
Create a new retrofit client and set it in the RestAdapter.Builder().setClient(). This involves parsing the Request object and returning the json as a Response object.
Implement this annotated interface as a mock class and use that in place of the version provided by RestAdapter.create() (wont test gson serialisation)
?
Ideally I want to have the mocked server provide json responses so I can test the gson serialisation at the same time.
Any examples would be greatly appreciated.
I decided to try method 1 as follows
public class MockClient implements Client {
@Override
public Response execute(Request request) throws IOException {
Uri uri = Uri.parse(request.getUrl());
Log.d("MOCK SERVER", "fetching uri: " + uri.toString());
String responseString = "";
if(uri.getPath().equals("/path/of/interest")) {
responseString = "JSON STRING HERE";
} else {
responseString = "OTHER JSON RESPONSE STRING";
}
return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST, new TypedByteArray("application/json", responseString.getBytes()));
}
}
And using it by:
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setClient(new MockClient());
It works well and allows you to test your json strings without having to contact the real server!
这篇关于用于测试的 Square 改造服务器模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!