What is the correct way to mock observable RxJava

I have an API that returns Observablefor use with RxJava. For testing, I want to avoid network operations, so we plan to mock the answers. However, since all answers should be wrapped using Observable, and the method from()expects Futurenot to be a specific type, my layout class is messed up with anonymous wrapper classes, and I think there should 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?

+4
source share
2 answers
return Observable.just(new MyData());

. mock = > .

+8

Observable.defer(() -> Observable.just(new MyData()) PublishSubject . : .defer(),

+1

Source: https://habr.com/ru/post/1651023/


All Articles