I am writing an instrumented test for an activity using ActivityTestRule
which will open a second activity by pressing a button on the under test (first) activity.
The problem is, the second activity uses dependency injection to inject a viewmodel factory to create its view model, but during tests, injection is disabled. Instead, while testing the second activity directy, a custom factory which contains a mocked viewmodel is set as the activity.viewModelFactory
to mock the view model behavior. But in the situation explained above, the first activity tries to open the second activity with injection disabled and also no factory manually set, so the test will fail with the following error:
kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized
To have a better picture of the scenario, this is the test that I am trying to run:
@Test
fun testLogin() {
// ... mock server configuration
onView(withId(R.id.etEmail))
.perform(typeText("dummyUserName")) // enter username
onView(withId(R.id.etPassword))
.perform(typeText("dummyPassword"), closeSoftKeyboard()) // enter password
onView(withId(R.id.btLogin))
.perform(click()) // click on login: this is where the second activity will try to be opened and the error occurs.
}
And this is how the second activity accesses its view model:
class SecondActivity : AppCompatActivity() {
@Inject // 1. injection is disabled during tests.
lateinit var viewModelFactory: ViewModelProvider.Factory
private lateinit var viewModel: SecondActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
// 2. this line fails, because viewModelFactory is null.
viewModel = ViewModelProviders.of(this, viewModelFactory).get(SecondActivityViewModel::class.java)
}
...
}
Considering this, I was wondering if there is a workaround to avoid the second activity from opening (since its behavior is irrelevant here) or if there is a solution to have the dummy factory containing the mocked view model being used in the second activity while testing the first activity (how to initializing the viewModelFactory when the second activity is being opened).