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?
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();
}
}
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With