测试真实的服务器请求通常不是一个好主意。 有关此主题的有趣讨论,请参见此博客文章。 根据作者的说法,使用真实服务器是一个问题,因为:

可能会间歇性失效的另一个动静件

需要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 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);

或者,您可以使用OkHttpClient和NetworkBehavior模拟API响应。 请参阅此处的使用示例。

最后,如果您只想测试Retrofit Service,最简单的方法是创建一个模拟版本,该模拟版本会发出测试的模拟结果。 例如,如果您具有以下OkHttpClient服务接口:

public interface GitHub {

@GET("/repos/{owner}/{repo}/contributors")

Call> contributors(

@Path("owner") String owner,

@Path("repo") String repo);

}

然后,您可以为测试创建以下OkHttpClient:

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);

}

}

然后,您可以在测试中使用OkHttpClient来模拟所需的响应类型。 有关完整的示例,请参见此Retrofit示例的SimpleService和SimpleMockService的实现。

综上所述,如果您绝对必须连接到实际服务器,则可以将Retrofit设置为与自定义OkHttpClient同步工作:

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();

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐