测试实际服务器请求通常不是一个好主意。参见
this blog post有关该主题的有趣的讨论。根据作者,使用你的真实服务器是一个问题,因为:
Another moving piece that can intermittently fail
Requires some expertise outside of the Android domain to deploy the server and keep it updated
Difficult to trigger error/edge cases
Slow test execution (still making HTTP calls)
您可以通过使用模拟服务器(如OkHttp的MockWebServer)来模拟真实的响应结果,从而避免上述所有问题。例如:
@Test
public void test() throws IOException {
MockWebServer mockWebServer = new MockWebServer();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mockWebServer.url("").toString())
//TODO Add your Retrofit parameters here
.build();
//Set a response for retrofit to handle. You can copy a sample
//response from your server to simulate a correct result or an error.
//MockResponse can also be customized with different parameters
//to match your test needs
mockWebServer.enqueue(new MockResponse().setBody("your json body"));
YourRetrofitService service = retrofit.create(YourRetrofitService.class);
//With your service created you can now call its method that should
//consume the MockResponse above. You can then use the desired
//assertion to check if the result is as expected. For example:
Call call = service.getYourObject();
assertTrue(call.execute() != null);
//Finish web server
mockWebServer.shutdown();
}
如果您需要模拟网络延迟,可以按如下所示自定义响应:
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody("{}");
response.throttleBody(1024, 1, TimeUnit.SECONDS);
或者,您可以使用MockRetrofit和NetworkBehavior来模拟API响应。参见here一个如何使用它的例子。
最后,如果您只想测试您的Retrofit服务,最简单的方法是创建一个模拟版本,为您的测试发出模拟结果。例如,如果您有以下GitHub服务接口:
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
然后,您可以为测试创建以下MockGitHub:
public class MockGitHub implements GitHub {
private final BehaviorDelegate delegate;
private final Map>> ownerRepoContributors;
public MockGitHub(BehaviorDelegate delegate) {
this.delegate = delegate;
ownerRepoContributors = new LinkedHashMap<>();
// Seed some mock data.
addContributor("square", "retrofit", "John Doe", 12);
addContributor("square", "retrofit", "Bob Smith", 2);
addContributor("square", "retrofit", "Big Bird", 40);
addContributor("square", "picasso", "Proposition Joe", 39);
addContributor("square", "picasso", "Keiser Soze", 152);
}
@Override public Call> contributors(String owner, String repo) {
List response = Collections.emptyList();
Map> repoContributors = ownerRepoContributors.get(owner);
if (repoContributors != null) {
List contributors = repoContributors.get(repo);
if (contributors != null) {
response = contributors;
}
}
return delegate.returningResponse(response).contributors(owner, repo);
}
}
然后,您可以在测试中使用MockGitHub来模拟您正在查找的响应类型。有关完整的示例,请参阅Retrofit example的SimpleService和SimpleMockService的实现。
所有这一切,如果你绝对必须连接到实际的服务器,你可以设置Retrofit与自定义ImmediateExecutor同步工作:
public class ImmediateExecutor implements Executor {
@Override public void execute(Runnable command) {
command.run();
}
}
然后将其应用于在构建Retrofit时使用的OkHttpClient:
OkHttpClient client = OkHttpClient.Builder()
.dispatcher(new Dispatcher(new ImmediateExecutor()))
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
//Your params
.build();