什么用广场改造框架的时候是嘲笑一个服务器进行测试的最佳方式。
What's the best way to mock a server for testing when using the square retrofit framework.
可能的方式:
新建改造client并将其设置在RestAdapter.Builder()。setClient()。这需要解析请求对象,并返回JSON作为一个Response对象。
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.
实现此注释的接口为模拟类并用它代替由RestAdapter.create()(不会测试GSON序列化)所提供的版本
Implement this annotated interface as a mock class and use that in place of the version provided by RestAdapter.create() (wont test gson serialisation)
理想我想有嘲笑的服务器提供JSON响应,所以我可以在同一时间测试GSON序列化。
Ideally I want to have the mocked server provide json responses so I can test the gson serialisation at the same time.
任何例子是大大AP preciated。
Any examples would be greatly appreciated.
我决定尝试方法1如下:
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()));
}
}
和使用它是:
RestAdapter.Builder builder = new RestAdapter.Builder();
builder.setClient(new MockClient());
它运作良好,并允许你无需与真正的服务器测试你的JSON字符串!
It works well and allows you to test your json strings without having to contact the real server!