测试RxJava2 doOnComplete()

从下面的代码中可以看出,我试图测试在我的存储库中发生的doOnComplete()调用的行为.但是,当我使用Observable.just()模拟我的客户端的注入依赖项时,不再调用doOnComplete().我认为这是故意的,根据Rx
Java2.我不确定如何解决这个问题.

@Singleton
public class Repository {
    private SomeNetworkClient client;
    private SomeCache cache;

    @Inject
    public Repository(SomeNetworkClient client, SomeCache cache) {
        this.client = client;
        this.cache = cache;
    }

    public Observable<SomeItem> getSomeItem() {
        return client.getSomeItem()
                .doOnComplete(() -> cache.doThisOnComplete())
                .doOnError(throwable -> someError);
    }
}

public class RepositoryTest {
    private Repository testedRepository;
    @Mock
    SomeNetworkClient client;
    @Mock
    SomeCache cache;
    @Mock
    SomeItem someItem;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        testedRepository = new Repository(client, cache);
        when(client.getSomeItem())
            .thenReturn(Observable.just(someItem));
    }

    @Test
    public void thisTestFails() {
        testedRepository.getSomeItem().blockingFirst();
        // This fails because it appears that mocking with
        // Observable.just() makes doOnComplete() not be invoked.
        verify(cache.doThisOnComplete());
    }
}

最佳答案 您的代码中的问题是,
blockingFirst()无需监听完整事件的发生.它将立即返回流和
dispose from observable中的第一个项目.

相反,您可以这样执行断言:


    testedRepository
            .getSomeItem()
            .test()
            .assertComplete()

点赞