Android单元测试LiveData.value返回null



我正在尝试使用MVVM体系结构为我的应用程序示例创建单元测试。在这个场景中,我试图为执行插入的方法创建一个测试,在这种情况下,我调用ViewModel方法,该方法调用将文本传递给插入的存储库,而我的存储库反过来调用Dao类的插入,然后返回一个插入了新项的新列表。但在我的测试中,我的LiveData对象是空

ViewModel类

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
}
}
}

存储库类

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

我的测试类

@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

为了解决这个问题,我只错过了一件事,我的方法viewmodel.insertTask((没有调用repository.getAllTodos((,那么我的anywhere就错了!!!正确的是:

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

最新更新