Android Unit Test LiveData.value return null

Viewed 1820

I'm trying to create unit tests for my app sample using the MVVM architecture. in the scenario, I'm trying to create a test for the method that performs the insert, in this case, I call the ViewModel method that calls the repository passing the text to the insert, and my repository, in turn, calls the insert of the Dao class and then returns a new list now with that new item inserted. But in my test, my LiveData object is coming as null

ViewModel class

class MainViewModel(private val todoRepository: TodoRepository) : ViewModel() {
    private val _todos = MutableLiveData<List<Todo>>()
    fun observeTodos() = _todos

    fun insertNewTask(text: String){
        viewModelScope.launch {
            val result  = todoRepository.insertTask(text)
            _todos.value = result
        }
    }
}

Repository class

class TodoRepositoryImpl(context: Context): TodoRepository {

val db =
    AppDatabase.invoke(
        context
    )

    override suspend fun insertTask(text: String): List<Todo>  {
        db.myDao().addItem(Todo(text = text))
        return db.myDao().getItems()
    }

}

my test class

@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class MainViewModelTest {

@Rule
@JvmField
val rule = InstantTaskExecutorRule()

private val repository = mock(TodoRepository::class.java)

private lateinit var viewModel: MainViewModel

@Before
fun setUp() {
    viewModel = MainViewModel(repository)
}

@Test
fun should_insertNewTodo() = runBlockingTest {

    //given
    val result = MutableLiveData<List<Todo>>()
    val returnedList = createTodoList()
    whenever(repository.getAllTodos()).thenReturn(returnedList)

    //when
    viewModel.insertNewTask("newTask")
    result.value = viewModel.observeTodos().value


    //than
    verify(repository).insertTask(anyString())
    assertEquals(returnedList, result.value)

}

fun createTodoList(): List<Todo>{
    val mockList = listOf(Todo(id = 1, text = "FIRST", completed = false),
        Todo(id = 2, text = "SECOND", completed = false),
        Todo(id = 3, text = "THIRD", completed = true)
    )
    return mockList
}

}

I think that is a easy, but I don't know ow to solve it, the test fail with this answer:

Expected :[Todo(id=1, text=FIRST, completed=false), Todo(id=2, text=SECOND, completed=false), Todo(id=3, text=THIRD, completed=true)]
Actual   :null
1 Answers

For resolve this problem I just miss one thing, my method viewmodel.insertTask() don't call repository.getAllTodos(), then my whenever are wrong!!! the correct is:

@Test
fun should_insertNewTodo() = runBlockingTest {

    //given
    val returnedList = createTodoList()
    whenever(repository.insertTask(anyString())).thenReturn(returnedList)

    //when
    viewModel.insertNewTask("newTask")
    val result = viewModel.observeTodos().value

    //than
    verify(repository).insertTask(anyString())
    assertEquals(returnedList, result)

}
Related