测试RxJava2 - observable不会返回任何值

时间:2017-11-12 17:31:18

标签: android unit-testing rx-android

我使用Robolectric和RxJava进行单元测试有问题,并且不知道我做错了什么。问题是创建的Observable中的代码没有返回任何错误或响应(onCompleted和onNext未被调用)我尝试创建简单测试,检查我的CategoriesManagerInteractor是否从数据库中获取正确的数据(对于数据库我使用SQLBrite + SQLDelight)。

测试代码:

@Test
public void categoriesManagerTest() {

    assertNotNull(BMApp.getBriteDatabase());

    //given

    //creating expected categories and adding it to database
    List<Category> expectedCategories = new ArrayList<>();
    expectedCategories.add(Category.FACTORY.creator.create(CategoryHelper.addCategory("Test 1"), "Test 1"));
    expectedCategories.add(Category.FACTORY.creator.create(CategoryHelper.addCategory("Test 2"), "Test 2"));

    CategoriesManagerInteractor interactor = new CategoriesManagerInteractor();
    TestObserver<List<Category>> testObserver = new TestObserver<>();
    Observable<List<Category>> observable = interactor.getCategoriesObservable();


    //when
    testObserver.awaitTerminalEvent(2, TimeUnit.SECONDS);
    observable.subscribeOn(Schedulers.trampoline()).observeOn(Schedulers.trampoline()).subscribe(testObserver);

    //then
    testObserver.assertNoErrors();
    assertEquals(2, observable.blockingFirst().size()); //success
    testObserver.assertComplete(); //fails
    assertEquals(2, testObserver.values().size()); //fails
}

创建Observable的CategoriesManagerInteractor方法:

 @Override
public io.reactivex.Observable<List<Category>> getCategoriesObservable() {
    return BMApp.getBriteDatabase().createQuery(Category.TABLE_NAME, Category.SELECT_ALL).mapToList(new Function<Cursor, Category>() {
        @Override
        public Category apply(Cursor cursor) throws Exception {
            return Category.FACTORY.select_allMapper().map(cursor);
        }
    });
}

0 个答案:

没有答案