Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MockWebServer and Retrofit with Callback

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.

like image 384
lukjar Avatar asked Jun 30 '14 12:06

lukjar


1 Answers

For retrofit 2 see the answer here: https://github.com/square/retrofit/issues/1259 You can supply the synchronous executor to an OkHttpClient (via its dispatcher) and set this client to the Retrofit.Builder. You can also set the same executor to the callbackExecutor.

For example:

CurrentThreadExecutor currentThreadExecutor = new CurrentThreadExecutor();
okhttp3.Dispatcher dispatcher = new okhttp3.Dispatcher(currentThreadExecutor);
OkHttpClient okHttpClient = new 
OkHttpClient.Builder().dispatcher(dispatcher).build();

new Retrofit.Builder()
        .client(okHttpClient)
        .baseUrl(httpUrl)
        .addConverterFactory(JacksonConverterFactory.create())
        .callbackExecutor(currentThreadExecutor)
        .build();

Example of CurrentThreadExecutor implementation: https://gist.github.com/vladimir-bukhtoyarov/38d6b4b277d0a0cfb3af

like image 174
jorichard Avatar answered Sep 29 '22 05:09

jorichard