Hi Following is my part of code which I want to test with various requests but I am unable to test as it is observable subscriber patter any idea how to mock subscriber or how to wait for a result in unit testing
api.loadData(request)
.observeOn(schedulers.main())
.doOnNext(this::addDataCheck)
.subscribe(
data -> onDataLodaded(listener, data),
e -> onAdFailedToLoad(listener, Api.error(request), e)
)
.addTo(disposables);
If you have access to the Observable you could use the
test()method of Observable to get aTestObserveror useblocking*()methods likeblockingSubscribe(),blockingFirst(), etc.In most cases you won't have access to them or you have already called
subscribe()on them. Then the answer depends on the JUnit version you are using.In general you will have to change the Handler for the RxJava and RxAndroid schedulers like this:
With this all your tasks will be run on the test thread of the JUnit test.
JUnit 4
JUnit 4 uses
Rules to change behaviour for all test methods, like changing the Schedulers of RxJava, for this extendTestRuleand implement the methods as needed. Rules are used like this:See the official wiki or for example here for more information about
Rules.JUnit 5
JUnit 5 uses
Extensions instead ofRules to apply modifications to all test methods. You could for example use this class:in your test like this:
More information about extensions are in the official user guide or for example here.
Because the question is tagged with "android", here a reminder that a
Rule/Extensionfor the scheduling ofLiveDatahas to be added if it is used.