MockWebServer and Retrofit with Callback

I would like to simulate a network connection using MockWebServer. Unfortulately retrofit callbacks are never referenced. My code is:

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 a modification without callbacks, it works.

+7
android retrofit mockwebserver
source share
1 answer

With Callback , you indicate that Retrofit is calling the request and the callback is being called asynchronously. This means that your test comes out before something happens.

There are two ways to make this work:

  • Use the lock at the end of the test and wait until one of the callback methods is called.
  • Pass the instance of the synchronous Executor (the one that simply calls .run() immediately) to setExecutors in RestAdapter.Builder so that synchronous callbacks and callbacks are executed synchronously.
+12
source share

All Articles