java - RxJava: How to unit test that an Observable is observed on and subscribed on the right scheduler? -
i have following scenario:
interface itemsrepository { observable<list<item>> getitems(); } class getitems { private scheduler ioscheduler; private scheduler mainscheduler; private itemsrepository itemsrepository; getitems(scheduler ioscheduler, scheduler mainscheduler, itemsrepository itemsrepository) { this.ioscheduler = ioscheduler; this.mainscheduler = mainscheduler; this.itemsrepository = itemsrepository; } observable execute(susbscriber subscriber) { return itemsrepository.getitems() .subscribeon(ioscheduler) .observeon(mainscheduler) .subscribe(subscriber); } }
now want unit test subscribeon
, observeon
called using correct scheduler
s.
the way did writing 2 unit tests follows:
@runwith(mockitojunitrunner.class) class getitemstest { private getitems getitems; private testscheduler ioscheduler = schedulers.test(); private testscheduler mainscheduler = schedulers.test(); private testsubscriber<list<item>> subscriber = new testsubscriber(); private list<item> items; @mock private itemsrepository itemsrepository; @before private void setup() { getitems = new getitems(ioscheduler, mainscheduler, itemsrepository); items = anylistof(item.class); given(itemsrepository.getitems()).willreturn(observable.just(items)); getitems.execute(); } @test public void should_subscribe_repository_on_the_io_scheduler throws exception { subscriber.assertnovalues(); mainscheduler.triggeractions(); subscriber.assertnovalues(); } @test public void should_observe_repository_on_the_main_scheduler() throws exception { subscriber.assertnovalues(); ioscheduler.triggeractions(); subscriber.assertnovalues(); mainscheduler.triggeractions(); subscriber.assertvalue(trendingdestinations); } }
i wandering if there better solution. triggering actions in order (io first , main) not cover case accidentally use ioscheduler twice. also, second test doesn't defend using mainscheduler twice well. solution, while defending against right things, not readable , not tell reader how testing states in name of test method. using solution now, appreciate suggestions.
Comments
Post a Comment