Unit testing android application with retrofit and rxjava

前端 未结 6 403
旧巷少年郎
旧巷少年郎 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:30

    Solution be @maciekjanusz is perfect along with explanation, so I will only say this, the problem occurs when you use Schedulers.io() and AndroidSchedulers.mainThread(). The problem with @maciekjanusz's answer is that it's too complex to understand and still not everyone uses Dagger2 (which they should). Also, I'm not too sure but with RxJava2 my imports for RxJavaHooks wasn't working.

    Better solution for RxJava2:-

    Add RxSchedulersOverrideRule to your test package and just add the following line in your test class.

    @Rule
    public RxSchedulersOverrideRule schedulersOverrideRule = new RxSchedulersOverrideRule();
    

    That's it, nothing else to add, your test cases should be running fine now.

提交回复
热议问题