Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to mock an RxJava Observable

I have an API which returns Observable's to be used with RxJava. For testing I want to avoid network operations so plan to mock the responses. However as all responses must me wrapped with Observable and the from() method expects a Future not a concrete type, my mock class is convoluted with anonymous wrapper classes and I think there must be a better way.

Here is what I have:

public class MockApi implements MyApi {

    @Override
    public Observable<MyData> getMyData() {
        return Observable.from(new Future<MyData>() {

            @Override public boolean cancel(boolean mayInterruptIfRunning) { return false; }
            @Override public boolean isCancelled() { return false; }
            @Override public boolean isDone() { return false; }

            @Override
            public MyData get(long timeout, TimeUnit unit) throws InterruptedException,
                    ExecutionException, TimeoutException {
                return get();
            }

            @Override
            public MyData get() throws InterruptedException, ExecutionException {
                return new MyData();
            }

        });
    }

    ...

}

Is there a better way?

like image 427
Nick Cardoso Avatar asked Aug 12 '16 07:08

Nick Cardoso


People also ask

How do you test a RxJava code?

Testing RxJava Using a TestSubscriberList<String> letters = Arrays. asList("A", "B", "C", "D", "E"); TestSubscriber<String> subscriber = new TestSubscriber<>(); Observable<String> observable = Observable . from(letters) . zipWith( Observable.

What is RxJava Observable?

An Observable is like a speaker that emits the value. It does some work and emits some values. An Operator is like a translator which translates/modifies data from one form to another form. An Observer gets those values.

How do I stop Observable RxJava?

using() and subscribe to the Observable with a Subscriber so you can call subscriber. unsubscribe() when the user clicks the button to cancel. Here's an outline. This will stop the observable stream and call socketDisposer() to stop the network activity.


2 Answers

return Observable.just(new MyData());

You can find the documentation here. And for more complicated mock => list of creating operators.

like image 123
Kevin Robatel Avatar answered Nov 07 '22 13:11

Kevin Robatel


You can use Observable.defer(() -> Observable.just(new MyData()), or use PublishSubject for sending data through it. Notice, you have to use .defer() operator in first case because it will use the same value from first call otherwise

like image 34
Alex Shutov Avatar answered Nov 07 '22 11:11

Alex Shutov