Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava2 with JUnit: no exceptions thrown in tests

The code below won't crash when running in JUnit environment. But it crashes when running in the app. I can see error logs in the console, but tests are marked as passed.

  @Test
  public void test() {
    Observable observable = Observable.error(new RuntimeException());
    observable.subscribe();
  }

So, the question is: how to make it crash in JUnit. Because yeah, if something doesn't work in the app it's a good thing if it doesn't work in the unit tests also :)

And in this example I have direct access to the observable. But in my real tests I don't have that. Real observables are just internal details of classes that being tested. The most thing I can to do is to inject schedulers or something.

So, how to make it crash without having direct access to the observable?

Also, I've just checked this code doesn't crash either:

  @Test
  public void test() {
    Observable observable = Observable.error(new RuntimeException());
    observable.subscribe(new Consumer() {
      @Override
      public void accept(Object o) throws Exception {
        throw new RuntimeException();
      }
    }, new Consumer<Throwable>() {
      @Override
      public void accept(Throwable throwable) throws Exception {
        throw new RuntimeException();
      }
    });
  }
like image 689
Dmitry Ryadnenko Avatar asked Aug 26 '26 15:08

Dmitry Ryadnenko


1 Answers

According to akarnokd this is RxJava2 specific problem.

"Such usages no longer throw synchronously in 2.x but end up in the plugin handler for errors."

It is possible to check if any errors was thrown with this code

public static List<Throwable> trackPluginErrors() {
    final List<Throwable> list = Collections.synchronizedList(new ArrayList<Throwable>());

    RxJavaPlugins.setErrorHandler(new Consumer<Throwable>() {
        @Override
        public void accept(Throwable t) {
            list.add(t);
        }
    });

    return list;
}
like image 136
Dmitry Ryadnenko Avatar answered Aug 29 '26 07:08

Dmitry Ryadnenko



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!