znat
znat

Reputation: 13474

How to mock a retrofit service observable calling onError?

I am testing this code.

service.getProducts()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<Result<Catalog<SoajsProductPreview>>>() {

                @Override
                public void onError(Throwable e) {
                    view.showErrorView(e);
                }

                @Override
                public void onNext(Result<Product>  products) {
                   view.showProducts(products)
                }

                @Override
                public void onCompleted() {}
            });

Testing that view.showProducts() the mocked service returns results works fine. I do

when(service.getProducts().thenReturn(someObservable);

Now I want to test that view.ShowErrorView() is called when the service throws an error but I can't find a way to do that:

Obviously the following doesn't compile

when(service.getProducts().thenReturn(someException); 

And this throws an exception immediately but doesn't call the Subscriber's onError method

when(service.getProducts().thenReturn(someException); 

How can I get Subscriber.onError() called?

Upvotes: 4

Views: 3198

Answers (1)

JohnWowUs
JohnWowUs

Reputation: 3083

when(service.getProducts().thenReturn(Observable.error(someException))

should work. See the documentation starting here.

Upvotes: 16

Related Questions