Search code examples
androidandroid-testingandroid-viewmodelinstrumented-test

How to get lifecycle owner in instrumented test android?


I have view model which can be provided via such code:

val retrofitService = RetrofitService.getInstance(requireContext())
val mainRepository = MainRepository(retrofitService)
val viewVM = ViewModelProvider(this, AppVMFactory(mainRepository)).get(AppViewModel::class.java)

and I would like to test my viewmodel requests and so on. Due to the fact that I will need context for my test I decided to use instrumented test where I can get the context via such line:

val appContext = InstrumentationRegistry.getInstrumentation().targetContext

the problem that I have is connected with getting lifecycle owner inside the test. The ViewModelProvider has such constructors:

constructor(
    private val store: ViewModelStore,
    private val factory: Factory,
    private val defaultCreationExtras: CreationExtras = CreationExtras.Empty,
) 

and:

constructor(owner: ViewModelStoreOwner, factory: Factory) : this(
        owner.viewModelStore,
        factory,
        defaultCreationExtras(owner)
    )

they are very similar. But how I can create viewmodel inside my test? Is it possible or it only can be done via totally different way?


Solution

  • This is my solution of this problem:

    private val appContext: Context = InstrumentationRegistry.getInstrumentation().targetContext
    
        @Test
        fun simpleLogIn() {
            val scenario = launchActivity<HomeScreen>()
            scenario.onActivity { activity ->
                val retrofitService = RetrofitService.getInstance(appContext)
                val mainRepository = MainRepository(retrofitService)
                val viewVM =
                    ViewModelProvider(
                        activity,
                        AppVMFactory(mainRepository)
                    )[AppViewModel::class.java]
            }
    
        }
    

    here as you can see I use launchActivity scenario. To enable it you should use in the build.gradle such dependency:

    androidTestImplementation 'androidx.test:core-ktx:X.X.X'