android - 如何确保在 Android 单元测试中调用 ViewModel#onCleared?

标签 android unit-testing android-testing android-architecture-components android-viewmodel

这是我的 MWE 测试类,它依赖于 AndroidX、JUnit 4 和 MockK 1.9:

class ViewModelOnClearedTest {
    @Test
    fun `MyViewModel#onCleared calls Object#function`() = mockkObject(Object) {
        MyViewModel::class.members
            .single { it.name == "onCleared" }
            .apply { isAccessible = true }
            .call(MyViewModel())

        verify { Object.function() }
    }
}

class MyViewModel : ViewModel() {
    override fun onCleared() = Object.function()
}

object Object {
    fun function() {}
}

注意:该方法在父类(super class) ViewModel 中受到保护。

我想验证 MyViewModel#onCleared 是否调用了 Object#function。上面的代码通过反射完成了这个。我的问题是:我能否以某种方式运行或模拟 Android 系统,以便调用 onCleared 方法,这样我就不需要反射了?

来自 onCleared JavaDoc:

This method will be called when this ViewModel is no longer used and will be destroyed.

所以,换句话说,我如何创建这种情况,以便我知道调用了 onCleared 并且我可以验证它的行为?

最佳答案

在 kotlin 中,您可以使用 public 覆盖 protected 可见性,然后从测试中调用它。

class MyViewModel: ViewModel() {
    public override fun onCleared() {
        ///...
    }
}

关于android - 如何确保在 Android 单元测试中调用 ViewModel#onCleared?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54115627/

相关文章:

c# - resharper test runner - 如何按类别执行?

android - 假 KeyEvent 不能*完全*像 "real"按钮一样工作。为什么?

Android 6.0上的Android文件权限

unit-testing - Visual Studio 测试中的 RowTest?

javascript - 期待这样或那样,如何在单元测试中包含 OR

android - 我怎样才能在 Espresso 中得到应用程序?

android - Espresso 测试失败 : Wanted to match 1 intent, 实际上匹配了 2 个 Intent

android-fragments - 无法解析androidx.fragment的依赖项:fragment-testing

android - 房间数据库在 macbook pro m1 中不起作用

android - 将 AudioEffect 附加到全局混音的首选方法?