MockWebServer和带回调的改造

MockWebServer和带回调的改造

本文介绍了MockWebServer和带回调的改造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想模拟MockWebServer的网络通信.不幸的是,从未调用过改装回调.我的代码:

I would like to simulate network communication by MockWebServer. Unfortulatelly retrofit callbacks are never invoking. My code:

    MockWebServer server = new MockWebServer();
    server.enqueue(new MockResponse().setResponseCode(200).setBody("{}"));
    server.play();

    RestAdapter restAdapter = new RestAdapter.Builder().setConverter(new MyGsonConverter(new Gson()))
            .setEndpoint(server.getUrl("/").toString()).build();

    restAdapter.create(SearchService.class).getCount(StringUtils.EMPTY,
            new Callback<CountContainer>() {

                @Override
                public void success(CountContainer countContainer, Response response) {
                    System.out.println("success");
                }

                @Override
                public void failure(RetrofitError error) {
                    System.out.println("error");
                }
            });

    server.shutdown();

当我使用不带回调的改装时,它可以工作.

When i use retrofit without callbacks it works.

推荐答案

通过具有 Callback ,您告诉Retrofit调用请求并异步调用回调.这意味着您的测试将在任何事情发生之前退出.

By having a Callback you are telling Retrofit to invoke the request and call the callback asynchronously. This means that your test is exiting before anything happens.

有两种方法可以使它起作用:

There are two ways to get this to work:

  • 在测试结束时使用锁,并等到其中一种回调方法被调用.
  • 将同步的 Executor 的实例(立即调用 .run()的实例)传递给 RestAdapter上的 setExecutors .builder ,以便后台调用和回调调用同步进行.
  • Use a lock at the end of the test and wait until one of the callback methods are invoked.
  • Pass an instance of a synchronous Executor (one that just calls .run() immediately) to setExecutors on the RestAdapter.Builder so that the background invocations and callback invocations happen synchronously.

这篇关于MockWebServer和带回调的改造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 23:18