Android单元测试LiveData.value返回null
我正在尝试使用MVVM架构为我的应用程序示例创建单元测试。在这个场景中,我试图为执行插入的方法创建一个测试,在本例中,我调用ViewModel方法,该方法调用存储库,将文本传递给插入,我的存储库反过来调用Dao类的插入,然后返回一个新列表,其中插入了新项。但是在我的测试中,我的LiveData对象是空的 ViewModel类Android单元测试LiveData.value返回null,android,unit-testing,kotlin,android-livedata,Android,Unit Testing,Kotlin,Android Livedata,我正在尝试使用MVVM架构为我的应用程序示例创建单元测试。在这个场景中,我试图为执行插入的方法创建一个测试,在本例中,我调用ViewModel方法,该方法调用存储库,将文本传递给插入,我的存储库反过来调用Dao类的插入,然后返回一个新列表,其中插入了新项。但是在我的测试中,我的LiveData对象是空的 ViewModel类 class MainViewModel(private val todoRepository: TodoRepository) : ViewModel() { pr
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
}
}
}
为了解决这个问题,我只错过了一件事,我的方法viewmodel.insertTask()不调用repository.getAllTodos(),那么我的方法就错了!!!正确答案是:
@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)
}
@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
}
}
Expected :[Todo(id=1, text=FIRST, completed=false), Todo(id=2, text=SECOND, completed=false), Todo(id=3, text=THIRD, completed=true)]
Actual :null
@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)
}