Unit testing android application with retrofit and rxjava

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

    I had the same problem with

    .observeOn(AndroidSchedulers.mainThread())

    i fixed it with the following codes

    public class RxJavaUtils {
        public static Supplier getSubscriberOn = () -> Schedulers.io();
        public static Supplier getObserveOn = () -> AndroidSchedulers.mainThread();
    }
    

    and use it like this

    deviceService.findDeviceByCode(text)
                .subscribeOn(RxJavaUtils.getSubscriberOn.get())
                .observeOn(RxJavaUtils.getObserveOn.get())
    

    and in my test

    @Before
    public void init(){
        getSubscriberOn = () -> Schedulers.from(command -> command.run()); //Runs in curren thread
        getObserveOn = () -> Schedulers.from(command -> command.run()); //runs also in current thread
    }
    

    works also for io.reactivex

提交回复
热议问题