Testing okHttp requests with Robolectric - callbacks

vkislicins

I have a function that I want to test which runs in an okHttp callback. I'm trying to test it using Robolectrics but the callback is never executed. I presume that is because the test moves on after request without waiting for okHttp to return. So far I've tried:

    ShadowLooper.pauseMainLooper();
    Robolectric.flushBackgroundScheduler();
    ShadowLooper.unPauseMainLooper();

but that didn't work. Any suggestions?

EDIT:

Here's an example of my code:

ApiClient.sendSomeDataToServer(data, callback);

Where ApiClient is a helper class containing okHttp client. sendSomeDataToServer API call looks something like this:

public static void sendSomeDataToServer(MyObject data, Callback callback){
    final Request request = new Request.Builder()
            .url(API_SOME_URL)
            .post(RequestBody.create(JSON, myObject.getAsJson().toString()))
            .build();
    sHttpClient.newCall(request).enqueue(callback);
}

Where sHttpClient is an initialised OkHttpClient.

I can test the execution of above by forcing Thread.sleep(5000) inside my test code and providing custom callback. The code I'm trying to test is inside the callback. Any suggestions how I can test that? I really don't want to change the main code to fit the test framework - should be the other way round.

Eugen Martynov

Lets assume you have next code. Interface:

@GET("/user/{id}/photo")  
void listUsers(@Path("id") int id, Callback<Photo> cb);

Implementation:

public void fetchData() {
    RestAdapter restAdapter = new RestAdapter.Builder()
                .setServer("baseURL")     
                .build();
    ClientInterface service = restAdapter.create(ClientInterface.class);

    Callback<Photo> callback = new Callback<Photo>() {
        @Override
        public void success(Photo o, Response response) {

        }

        @Override
        public void failure(RetrofitError retrofitError) {

        }
    };
    service.listUsers(435, callback);
}

First of all you need to change service instantiation to service injection (as parameter or field). I will do it as parameter:

public void fetchData(ClientInterface clients) {
}

After this text is quite trivial:

@Test
public void checkThatServiceSuccessIsProcessed() {
    ClientInterface mockedClients = mock(ClientInterface.class);

    activity.fetchData(mockedClients);

    // get callback
    ArgumentCaptor<Callback<Photo>> captor = (ArgumentCaptor<Callback<Photo>>)ArgumentCaptor.forClass(Callback.class);
    verify(mockedInterface).listUsers(anything(), captor.capture());
    Callback<Photo> passedCallback = captor.value();
    // run callback
    callback.success(...);
    // check your conditions
}

The used library for mocking and verifying is Mockito.

There will be one warning with captor instantiation because of generics but it fixable if you will use @Captor annotation instead of creating captor by hands.

The parameter injection is not perfect, especially for case of activities. This was used to simplify example. Consider for proper injection with library or without. I would encourage you to try Dagger for injections

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Testing retrofit 2 with robolectric, callbacks not being called

From Dev

while calling more than one async requests with OkHttp, sometimes callbacks are interfered

From Dev

Robolectric test that uses OkHttp for real HTTP requests throws java.lang.NullPointerException: No password supplied for PKCS#12 KeyStore

From Dev

Testing AsyncTaskLoaders with Robolectric

From Dev

Testing Fragments with Robolectric 3.0

From Dev

Android http testing with Robolectric

From Dev

Testing with SugarORM and Robolectric

From Dev

Robolectric app testing with Firebase

From Dev

Testing AsyncTaskLoaders with Robolectric

From Dev

Android Testing with Robolectric and Dagger

From Dev

Robolectric app testing with Firebase

From Dev

Android - Robolectric testing With RxAndroid?

From Dev

Testing Fragments with Robolectric 3.0

From Dev

Okhttp response callbacks on the main thread

From Dev

Testing Asynchronous Callbacks with Jasmine

From Dev

Retrofit testing, callbacks?

From Dev

Testing node callbacks with mocha

From Dev

Testing Views of a Fragment with Robolectric 3.0

From Dev

Gradle Robolectric Resources NotFoundException in Testing

From Dev

RuntimeException when testing ListPreference with Robolectric

From Dev

Unit Testing RecyclerView OnItemTouchListener Robolectric

From Dev

Gradle Robolectric Resources NotFoundException in Testing

From Dev

Robolectric NullPointerException when testing adapters

From Dev

Robolectric 3.0 testing Vibrator service

From Dev

Testing Views of a Fragment with Robolectric 3.0

From Dev

Cache POST requests with OkHttp

From Dev

Writing jQuery callbacks for ajax requests

From Dev

OkHttp in android for making network requests

From Dev

OkHttp doesn't cache requests

Related Related

  1. 1

    Testing retrofit 2 with robolectric, callbacks not being called

  2. 2

    while calling more than one async requests with OkHttp, sometimes callbacks are interfered

  3. 3

    Robolectric test that uses OkHttp for real HTTP requests throws java.lang.NullPointerException: No password supplied for PKCS#12 KeyStore

  4. 4

    Testing AsyncTaskLoaders with Robolectric

  5. 5

    Testing Fragments with Robolectric 3.0

  6. 6

    Android http testing with Robolectric

  7. 7

    Testing with SugarORM and Robolectric

  8. 8

    Robolectric app testing with Firebase

  9. 9

    Testing AsyncTaskLoaders with Robolectric

  10. 10

    Android Testing with Robolectric and Dagger

  11. 11

    Robolectric app testing with Firebase

  12. 12

    Android - Robolectric testing With RxAndroid?

  13. 13

    Testing Fragments with Robolectric 3.0

  14. 14

    Okhttp response callbacks on the main thread

  15. 15

    Testing Asynchronous Callbacks with Jasmine

  16. 16

    Retrofit testing, callbacks?

  17. 17

    Testing node callbacks with mocha

  18. 18

    Testing Views of a Fragment with Robolectric 3.0

  19. 19

    Gradle Robolectric Resources NotFoundException in Testing

  20. 20

    RuntimeException when testing ListPreference with Robolectric

  21. 21

    Unit Testing RecyclerView OnItemTouchListener Robolectric

  22. 22

    Gradle Robolectric Resources NotFoundException in Testing

  23. 23

    Robolectric NullPointerException when testing adapters

  24. 24

    Robolectric 3.0 testing Vibrator service

  25. 25

    Testing Views of a Fragment with Robolectric 3.0

  26. 26

    Cache POST requests with OkHttp

  27. 27

    Writing jQuery callbacks for ajax requests

  28. 28

    OkHttp in android for making network requests

  29. 29

    OkHttp doesn't cache requests

HotTag

Archive