Unit testing android application with retrofit and rxjava

前端 未结 6 404
旧巷少年郎
旧巷少年郎 2020-12-08 16:13

I have developed an android app that is using retrofit with rxJava, and now I\'m trying to set up the unit tests with Mockito but I don\'t know how to mock the api responses

6条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 16:36

    Is there any particular reason you return Subscription from your api methods? It is usually more handy to return Observable (or Single) from api methods (especially regarding to Retrofit being able to generate Observables and Singles instead of calls). If there is no special reason, I'd recommend to switch to something like this:

    public interface Api {
        @GET("genres")
        Single> syncGenres();
        ...
    }
    

    so your calls to api will look like:

    ...
    Api api = retrofit.create(Api.class);
    api.syncGenres()
       .subscribeOn(Schedulers.io())
       .observeOn(AndroidSheculers.mainThread())
       .subscribe(genres -> soStuff());
    

    In that way, you'd be able to mock api class and write:

    List mockedGenres = Arrays.asList(genre1, genre2...);
    Mockito.when(api.syncGenres()).thenReturn(Single.just(mockedGenres));
    

    Also you'll have to consider that you won't be able to test responses on worker threads, since tests won't wait for them. For bypassing this problem I'd recommend reading these articles and consider using something like scheduler manager or transformer to be able to explicitly tell presenter which schedulers to use (real or test ones)

提交回复
热议问题