Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito - when arrange with RxJava 2 .retry()

I'm trying to learn how to test methods with .retry().

I have 2 basic classes:

public class Foo {

    private Bar bar;

    public Foo(Bar bar) {
        this.bar = bar;
    }

    public Completable execute() {
        return Completable.fromAction(() -> System.out.println("first part of task"))
                .andThen(bar.dangerousMethod()
                        .retry(10)
                )
                .andThen(Completable.fromAction(() -> System.out.println("sec part of task")));
    }
}


public interface Bar {
    Completable dangerousMethod();
}

Now I want to mock dangerousMethod to fail twice then emit complete()

@Mock private Bar bar;
@InjectMocks private Foo foo;

@Test
public void test() throws Exception {
    when(bar.dangerousMethod()).thenReturn(
            error(new Exception()),
            error(new Exception()),
            complete()
    );

    foo.execute()
            .test()
            .assertComplete();
}

Unfortunately it fails:

first part of task

java.lang.AssertionError: Not completed (latch = 0, values = 0, errors = 1, completions = 0)

and dangerousMethod() is executed 10 times but run only once, because of .retry() logic.

How to test the .retry() method using Mockito in a proper way?

like image 216
Lau Avatar asked May 29 '26 07:05

Lau


1 Answers

You should not test this method as it is not part of your code and it is (I hope) well tested by those guys who wrote RxJava library.

But anyway if you want to test that you can do it:

Replace your when statement with this:

   when(bar.dangerousMethod()).thenReturn(
                Completable.defer(new Callable<CompletableSource>() {
                    boolean fail = true;
                    @Override
                    public CompletableSource call() throws Exception {
                        if(fail) {
                            fail = false;
                            return Completable.error(new Exception());
                        } else {
                            return Completable.complete();
                        }
                    }
                }));
like image 155
RadekJ Avatar answered May 31 '26 06:05

RadekJ



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!