测试RxJava2 doOnComplete()

时间:2017-06-09 03:25:20

标签: java android unit-testing junit rx-java2

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

@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());
    }
}

1 个答案:

答案 0 :(得分:1)

代码中的问题是,blockingFirst()无法监听完整事件的发生。它会立即返回流中的第一个项目dispose from observable

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


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