楊惟鈞
楊惟鈞

Reputation: 632

RxJava2: TestSubscriber.AssertNoErrors always pass

I am testing some features of Rxjava2(2.0.7) and have some troubles in unit test

here is my code

    RxJavaPlugins.setErrorHandler(null);
    Observable<String> o = Observable.create((ObservableOnSubscribe<String>) e -> {
        String s = System.currentTimeMillis() + "";
        System.out.println("runing observable@" + s);
        throw new RuntimeException();
    }).delay(1, TimeUnit.SECONDS);

    o
            .doOnNext(x -> {
                System.out.println(x);
                throw new RuntimeException();
            })
            .doOnError(e->e.printStackTrace())
            .test()
            .assertNoErrors()
            .awaitCount(1)
            .awaitDone(5, TimeUnit.SECONDS);

The problem is this test always passed, but I can still find exception printed in log

What am I doing wrong?

Upvotes: 1

Views: 325

Answers (1)

yosriz
yosriz

Reputation: 10267

You just need to switch the order of execution, and put the assertNoErrors() at the end.

RxJavaPlugins.setErrorHandler(null);
    Observable<String> o = Observable.create((ObservableOnSubscribe<String>) e -> {
        String s = System.currentTimeMillis() + "";
        System.out.println("runing observable@" + s);
        throw new RuntimeException();
    })
            .delay(1, TimeUnit.SECONDS);

    o
            .doOnNext(x -> {
                System.out.println(x);
                throw new RuntimeException();
            })
            .doOnError(e -> e.printStackTrace())
            .test()
            .awaitCount(1)
            .awaitDone(5, TimeUnit.SECONDS)
            .assertNoErrors();

otherwise assertNoErrors() act immediately after you call the test() operator and the error still didn't propagate in the stream.
Genrally, you should first act with awaitXXX to wait for some expected event to happen, and then test it with assertXXX.

Upvotes: 1

Related Questions