测试真实的服务器请求通常不是一个好主意。有关该主题的有趣讨论,请参阅 this blog post。根据作者的说法,使用你的真实服务器是一个问题,因为:
- 另一个可能间歇性故障的移动部件
- 需要一些 Android 域之外的专业知识来部署服务器并保持更新
- 难以触发错误/边缘情况
- 测试执行缓慢(仍在进行 HTTP 调用)
您可以通过使用 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<YourObject> 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 的使用示例。
最后,如果您只想测试改造服务,最简单的方法是创建它的模拟版本,为您的测试发出模拟结果。比如你有如下GitHub服务接口:
public interface GitHub {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> contributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
然后您可以为您的测试创建以下MockGitHub:
public class MockGitHub implements GitHub {
private final BehaviorDelegate<GitHub> delegate;
private final Map<String, Map<String, List<Contributor>>> ownerRepoContributors;
public MockGitHub(BehaviorDelegate<GitHub> 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<List<Contributor>> contributors(String owner, String repo) {
List<Contributor> response = Collections.emptyList();
Map<String, List<Contributor>> repoContributors = ownerRepoContributors.get(owner);
if (repoContributors != null) {
List<Contributor> 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();
}
}
然后将其应用于您在构建改造时使用的OkHttpClient:
OkHttpClient client = OkHttpClient.Builder()
.dispatcher(new Dispatcher(new ImmediateExecutor()))
.build();
Retrofit retrofit = new Retrofit.Builder()
.client(client)
//Your params
.build();