0

我知道对于同一个问题有多个类似的问题,但似乎没有帮助我最终可能遗漏了一些东西。

我有一个调用 api 的视图模型,我正在尝试为我的视图模型方法编写 Junit,但出现以下错误

Wanted but not invoked:
apiHelper.getProfiles(
    <any com.package.MyInterface.GetProfilesListener>
);
-> at com.package.ApiHelper.getProfiles(ApiHelper.java:319)
Actually, there were zero interactions with this mock.

ProfileViewModel.kt

class ProfileViewModel @Inject constructor(
    private val data: Info
): ViewModel() {

    private val profilesList = MutableLiveData<List<Profile>>()
    fun getProfiles(): LiveData<List<Profile>> = profilesList

    fun onResume() {
        load()
    }

    private fun load() {
        viewModelScope.launch {
            data.apiHelper!!.getProfiles(
                object : MyInterface.GetProfilesListener {
                    override fun success(profiles: List<Profile>?) {
                        profilesList.postValue(profiles)
                    }

                    override fun failure() {
                        profilesList.postValue(null)
                    }
                })
        }
    }

}

ProfileViewModelTest.kt

class ProfileViewModelTest {

    @get:Rule
    var instantExecutionRule = InstantTaskExecutorRule()

    private val data: Info = mock()
    private val apiHelper: ApiHelper = mock()
    private lateinit var viewModel: ProfileViewModel
    private var observer: Observer<List<Profile>> = mock()

    @Before
    fun setup() {
        viewModel = ProfileViewModel(data)
        viewModel.getProfiles().observeForever(observer)
    }

    @Test
    fun `when api returns data then live data sets to it`() = runBlockingTest {
        doAnswer { invocationOnMock ->
            val listener = invocationOnMock.arguments[0] as MyInterface.GetProfilesListener
            listener.success(emptyList<Profile>())
        }.whenever(apiHelper).getProfiles(any())
        viewModel.onResume()
        verify(apiHelper).getProfiles(any())
        verify(observer).onChanged(emptyList())
    }

}

我觉得这是为 viewmodel 实现 junit 的正确方法,但不确定是否在这里遗漏了什么。非常感谢任何建议或帮助。

4

0 回答 0