即使我显式设置了模拟方法的返回值,为什么它仍返回null?

时间:2019-08-30 14:36:13

标签: android junit mockito viewmodel android-livedata

应该返回LiveData的方法在junit测试期间返回null。

我有以下类和接口:

class PersonListViewModel(personRepository: PersonRepository): ViewModel() {

    val personList: LiveData<List<Person>> = personRepository.getPersonList()
}

interface PersonRepository {
    fun getPersonList(): LiveData<List<Person>>
}

class PersonListViewModelTest {

    @get:Rule
    var rule: TestRule = InstantTaskExecutorRule()

    @Mock
    private lateinit var personListObserver: Observer<List<Person>>
    @Mock
    private lateinit var personRepository: PersonRepository

    private lateinit var viewModel: PersonListViewModel

    @Before
    fun setup() {
        MockitoAnnotations.initMocks(this)
        viewModel = PersonListViewModel(personRepository)

        val personList = listOf(Person("id1"), Person("id2"))
        val personListLiveData = MutableLiveData<List<Person>>()
        personListLiveData.postValue(personList)

        `when`(personRepository.getPersonList()).thenReturn(personListLiveData)

        //NullPointerException thrown here, personList is null
        viewModel.personList.observeForever(personListObserver) 
    }

    @Test
    fun testPersonListPopulates() {
        assertEquals(2, viewModel.personList.value?.size ?: 0)
    }
}

为什么该属性仍然为null,如何解决这个问题以测试是否填充了人员列表?

0 个答案:

没有答案