android - 将 Spek 与挂起方法一起使用
问题描述
我正在尝试在我的 Android Kotlin 项目中使用 Spek 框架和 nhaarman mockito kotlin 创建一个单元测试。问题是当有嵌套的挂起方法时,我不知道如何模拟响应。这就是我正在尝试的方式
我定义:
val testCoroutineDispatcher = TestCoroutineDispatcher()
val testCoroutineScope = TestCoroutineScope(testCoroutineDispatcher)
在任何描述之前
beforeGroup {
Dispatchers.setMain(testCoroutineDispatcher) //not sure if this is working properly
}
afterGroup {
Dispatchers.resetMain() // reset main dispatcher to the original Main dispatcher
testCoroutineScope.cleanupTestCoroutines()
}
这是我的小组
describe("Test view model") {
val contentRepository by memoized(CachingMode.SCOPE) { mock<ContentRepository>() }
val contentViewModel by memoized(CachingMode.SCOPE) {
ContentViewModel(contentRepository)
}
describe("When something happens") {
beforeGroup {
testCoroutineScope.runBlockingTest {
whenever(contentRepository.fetchAllContents(0, 10))
.thenReturn(Result.success(content))//This is suspend
contentViewModel.setContentPage(0)
}
}
it("should fetch all content from repository with page 0") {
verifyBlocking(contentRepository) {
fetchAllClassContents(0, 10)
}
}
}
}
})
但我收到以下错误
Argument(s) are different! Wanted:
classContentRepository.fetchAllClassContents(
0,
10,
Continuation at viewmodel.ContentViewModelSpek$1$3$1$4$1.invokeSuspend(ContentViewModelSpek.kt:92)
);
-> at repository.ContentRepository.fetchAllClassContents(ContentRepository.kt:23)
Actual invocation has different arguments:
contentRepository.fetchAllContents(
0,
10,
Continuation at viewmodel.ContentViewModel$setContentPage$1.invokeSuspend(ContentViewModel.kt:26)
);
似乎模拟、方法执行和断言在不同的范围内运行
我找不到任何可以帮助我使用协程创建测试的指南 在此先感谢
解决方案
推荐阅读
- svg - 如何在 Phaser 3 中与 SVG 图像进行悬停交互
- css - 如何制作按钮:hover 影响 java fx 中的 lebel
- node.js - 如何在 Docker 中使用 Chromium v77 运行 NodeJS puppeteer?
- python - Flask-SQLAlchemy 插入多个字典
- c# - 实现一个非常基本的 IDisposable
- python - 如何在 SymPy 中使用对数 x 轴正确编写 2D 绘图调用?
- python - 提高词袋模型中排名的效率
- python - 逐行读取.trc文件并使用python返回信息
- android - Android:当我设置 shouldOverUriLoading 返回 false 时,HTML 中的脚本无法调用 addEventListener
- java - 如何从其他方法访问列表?