使用 Koin 和 Kotlin 协程在 Android 中测试 ViewModel

Testing ViewModel in Android with Koin and Kotlin coroutines

我开始使用 Koin,我需要测试一个 ViewModel,它要求存储库从 phone 的内部存储中检索文件。

当我设置 ViewModel 测试时,我正在做:

@Before
    fun setup() {
        startKoin {
            modules(dataModule)
        }
        declareMock<Repository> {
            fakeAccount = moshiAccountAdapter.fromJson(json)
            whenever(this.getAccount()).thenReturn(fakeAccount)
        }
    }

但是存储库 getAccount 方法是 suspend fun getAccount(): Account?,所以我在 ViewModelTest class 中收到错误消息 suspend function getAccount should be called only from a coroutine or from another suspending function.

提前致谢!

您可以使用 runBlocking { } 块来 运行 挂起的函数进行测试