RxJava2: .andThen () вызван несмотря на то, что выдается первая ошибка Completable - PullRequest
0 голосов
/ 09 июня 2019

У меня 2 метода в методе, например:

completable1.doSomething()
    .andThen(completable2.doSomethingElse())

И я хочу проверить это, используя Mockito и возвращая ошибку в первом завершаемом файле. Вот мой оригинальный метод:

 public Completable updateQuestion(Question question){
    return gameRepositoryType.updateQuestion(question)
            .andThen(gameRepositoryType.getGameById(question.getqId())
                    .map(GAME_MAPPER)
                    .flatMapCompletable(gameRepositoryType::updateGame))
            .observeOn(AndroidSchedulers.mainThread());
}

А вот и мой тест:

@Test
public void updateQuestionError(){
    when(gameRepositoryType.updateQuestion(question)).thenReturn(Completable.error(error));
    when(question.getqId()).thenReturn(FAKE_QID);
    when(gameRepositoryType.getGameById(FAKE_QID)).thenReturn(Single.just(game));
    when(gameRepositoryType.updateGame(game)).thenReturn(Completable.complete());

    interactor.updateQuestion(question)
            .test()
            .assertNotComplete()
            .assertError(error);

    verify(gameRepositoryType).updateQuestion(question);       //this is called in test
    verify(question,never()).getqId();                         //this is called in test
    verify(gameRepositoryType,never()).getGameById(FAKE_QID);  //this is called in test
    verify(gameRepositoryType,never()).updateGame(game);       //this is NEVER called in test
}

В моих проверках в конце метода тестирования я ожидаю, что после того, как первый завершаемый файл выдаст ошибку, 3 последние проверки должны выполняться с успехом, то есть 3 последние verify() никогда не должны вызываться.

Однако я вижу, что все методы вызываются, хотя gameRepositoryType.updateQuestion(question) выдает ошибку. Почему это?

Разве нельзя andThen() никогда не вызываться, если первая завершаемая ошибка выдает?

1 Ответ

2 голосов
/ 09 июня 2019
completable1.doSomething()
    .andThen(completable2.doSomethingElse())

Разве нельзя вызывать andThen (), если первая завершаемая ошибка выдает?

andThen всегда будет вызывать completable2.doSomethingElse() для создания потока, но возвращаемый им Completable никогда не будет подписан.

Вы можете проверить это следующим образом:

when(completable1.doSomething()).thenReturn(Completable.error(error));

CompletableSubject completableSubject = CompletableSubject.create();
when(completable2.doSomethingElse()).thenReturn(completableSubject);


TestObserver testObserver = completable1.doSomething()
    .andThen(completable2.doSomethingElse()).test();

// Verify that completable2.doSomethingElse() was never subscribed to:
assertFalse(completableSubject.hasObservers());

testObserver
    .assertError(error)
    .assertNotComplete();

Редактировать: для уточнения:

Учитывая, что ваши методы определены следующим образом:

private Completable updateQuestion(Question question) {
    System.out.println("prints when the updateQuestion is called");
    return Completable.fromAction(() -> {
        System.out.println("prints when updateQuestion is subscribed to");
        database.updateQuestion(question);
    });
}

private Completable updateGame() {
    System.out.println("prints when the updateGame is called");
    return Completable.fromAction(() -> {
        System.out.println("prints when updateGame is subscribed to");
        database.updateGame();
    });
}

Предположим, вы звоните:

updateQuestion(question)
    .andThen(updateGame())
    .subscribe();

И database.updateQuestion(question); выдает ошибку.

Тогда ваш вывод журнала будет:

prints when the updateQuestion is called
prints when the updateGame is called
prints when updateQuestion is subscribed to
>> error 

и database.updateGame(); никогда не будут выполнены

...