How to correctly mock ViewModel on androidTest

后端 未结 4 2110
野性不改
野性不改 2021-02-13 03:21

I\'m currently writing some UI unit tests for a fragment, and one of these @Test is to see if a list of objects is correctly displayed, this is not an integ

4条回答
  •  爱一瞬间的悲伤
    2021-02-13 03:39

    Within your test setup you'll need to provide a test version of the FavoritesViewModelFactory which is being injected in the Fragment.

    You could do something like the following, where the Module will need to be added to your TestAppComponent:

    @Module
    object TestFavoritesViewModelModule {
    
        val viewModelFactory: FavoritesViewModelFactory = mock()
    
        @JvmStatic
        @Provides
        fun provideFavoritesViewModelFactory(): FavoritesViewModelFactory {
            return viewModelFactory
        }
    }
    

    You'd then be able to provide your Mock viewModel in the test.

    fun setupViewModelFactory() {
        whenever(TestFavoritesViewModelModule.viewModelFactory.create(FavoritesViewModel::class.java)).thenReturn(viewModel)
    }
    

提交回复
热议问题