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!