Sahil Patel
Sahil Patel

Reputation: 734

RxJava2 TestSubscriber assertEmpty always true

I am trying to test some RxJava code using TestSubsriber. The data is coming from Room ORM as Flowable<Task>.

This is how my DAO class looks right now.

@Dao
public interface TaskDao {

    @Insert()
    long insertTask(TaskEntity task);

    @Delete
    int deleteTask(TaskEntity task);

    @Query("SELECT * FROM task_table WHERE status = :taskStatus ORDER BY created_at DESC")
    Flowable<List<TaskEntity>> getAllTasks(String taskStatus);

    @Query("SELECT * FROM task_table WHERE id = :taskId")
    Flowable<TaskEntity> getTask(String taskId);

    @Update()
    int updateTask(TaskEntity updatedTask);

    @Query("SELECT COUNT(*) FROM task_table")
    int rowCount();
}

I am trying to test getTask() method. Here the exact test method that is failing.

@Test
public void getTask_getSavedTask_returnsTask() {

    Long resp = mTaskDao.insertTask(taskEntity);
    assertThat(resp, is(1L));

    assertThat(mTaskDao.rowCount(), is(1));

    Flowable<TaskEntity> response = mTaskDao.getTask(taskEntity.getTaskId());
    TestSubscriber<TaskEntity> testSubscriber = new TestSubscriber<>();

    response.subscribe(testSubscriber);
    testSubscriber.assertNoErrors();
    testSubscriber.assertValueCount(1);
}

This code snippet fails at testSubscriber.assertValueCount(1) method.

The model is getting saved in db since the returned value from insert call is > 1. Also the row count is getting increased.

I tried running the same kind of code from outside the test environment (from an activity) and it's working fine there.

Upvotes: 0

Views: 460

Answers (1)

akarnokd
akarnokd

Reputation: 69997

Looks like your DAO runs asynchronously and the TestSubscriber doesn't receive an answer immediately. Change the test to this and it should work:

testSubscriber.awaitCount(1, BaseTestConsumer.TestWaitStrategy.SLEEP_1MS, 5000);

testSubscriber.assertNoTimeout();
testSubscriber.assertNoErrors();
testSubscriber.assertValueCount(1);

Upvotes: 1

Related Questions