4

我正在为一个活动编写一个仪器测试,使用ActivityTestRule它将通过按下被测(第一个)活动上的按钮打开第二个活动。

问题是,第二个活动使用依赖注入来注入视图模型工厂以创建其视图模型,但在测试期间,注入被禁用。相反,在直接测试第二个活动时,将包含模拟视图模型的自定义工厂设置为activity.viewModelFactory模拟视图模型行为。但是在上面解释的情况下,第一个活动尝试打开第二个活动并禁用注入并且也没有手动设置工厂,因此测试将失败并出现以下错误:

kotlin.UninitializedPropertyAccessException: lateinit property viewModelFactory has not been initialized

为了更好地了解场景,这是我尝试运行的测试:

@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.
}

这就是第二个活动访问其视图模型的方式:

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)
    }

    ...

}

考虑到这一点,我想知道是否有一种解决方法来避免打开第二个活动(因为它的行为在这里无关紧要),或者是否有解决方案让包含模拟视图模型的虚拟工厂在测试时用于第二个活动第一个活动(打开第二个活动时如何初始化 viewModelFactory)。

4

0 回答 0