【问题标题】:Testing ViewModel in Android with Koin and Kotlin coroutines使用 Koin 和 Kotlin 协程在 Android 中测试 ViewModel
【发布时间】:2019-09-29 09:14:41
【问题描述】:

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

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

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

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

提前致谢!

【问题讨论】:

    标签: android kotlin kotlin-coroutines koin


    【解决方案1】:

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

    【讨论】:

    • 你到底是什么意思我应该这样做?
    • fun setUp() = runBlocking{ ...} 或挂起函数调用之间的任何位置。这个块实际上会启动一个协程,我建议阅读它以获得更深入的知识或对你有很大帮助的协程
    • 我已经试过了,AS说suspension functions can be called only within corutine body
    • 好吧,我刚刚将那个存根移到了测试中,它位于 runBlockingTest 内,因此它现在可以工作了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    • 2021-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多