Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava2 JUnit testing

I have some troubles with unit testing a RxJava code part. I want to test the method below. It is a presenter method.

public void onSearchQueryChanged(String searchQuery) {
    backendService.getShopResultsCount(searchQuery)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(result -> {
            if (isViewAttached()) {
                getView().hideShopSearchInProgress();
                getView().displayShopSearchResultCount(result.getSearchResponse().getNumberOfHits());
            }
        }, error -> {
            if (isViewAttached()) {
                getView().hideShopSearchInProgress();
            }
        });
}

In the best case I would like to mock the backendService and test this usecase for specific search queries and with attached/detached view.

I've done some research and I'm aware of toBlocking() and test() methods. They all assume I have the Observable available. I guess I have to split the method somehow. What would be your approach on that?

My stack: RxJava2, dagger, MVP.

like image 543
Marcin Kunert Avatar asked Nov 17 '25 20:11

Marcin Kunert


1 Answers

In our project we write code like:

Mockito.when(backendService.getShopResult(Mockito.any())).thenReturn(Observable.just(Some Data)

U can workaround schedulers by:

@Inject
Scheduler subscribeOn;

And in test pass Schedulers.test() or Schedulers.immediate()

or u cant use TestRule with RxJavaPlugins.registerSchedulersHook()

like image 67
Сергей Боиштян Avatar answered Nov 19 '25 08:11

Сергей Боиштян



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!