【发布时间】:2020-12-09 21:05:35
【问题描述】:
我正在尝试使用 Mockk 库测试多个服务器响应。类似于我在 this answer 中为 Mockito 找到的东西。
有我的示例 UseCase 代码,每隔几秒就会重复调用以从远程服务器加载系统,当远程系统包含的用户多于本地用户时,它会停止运行(执行onComplete)。
override fun execute(localSystem: System, delay: Long): Completable {
return cloudRepository.getSystem(localSystem.id)
.repeatWhen { repeatHandler -> // Repeat every [delay] seconds
repeatHandler.delay(params.delay, TimeUnit.SECONDS)
}
.takeUntil { // Repeat until remote count of users is greater than local count
return@takeUntil it.users.count() > localSystem.users.count()
}
.ignoreElements() // Ignore onNext() calls and wait for onComplete()/onError() call
}
为了测试这种行为,我正在使用 Mockk 库模拟 cloudRepository.getSystem() 方法:
@Test
fun testListeningEnds() {
every { getSystem(TEST_SYSTEM_ID) } returnsMany listOf(
Single.just(testSystemGetResponse), // return the same amount of users as local system has
Single.just(testSystemGetResponse), // return the same amount of users as local system has
Single.just( // return the greater amount of users as local system has
testSystemGetResponse.copy(
owners = listOf(
TEST_USER,
TEST_USER.copy(id = UUID.randomUUID().toString())
)
)
)
)
useCase.execute(
localSystem = TEST_SYSTEM,
delay = 3L
)
.test()
.await()
.assertComplete()
}
如您所见,我正在使用 returnsMany 答案,它应该在每次调用时返回不同的值。
主要问题是 returnsMany 每次都返回相同的第一个值,而 .takeUntil {} 永远不会成功,这意味着永远不会为此 Completable 调用 onComplete()。如何让returnsMany 在每次调用时返回不同的值?
【问题讨论】:
标签: android unit-testing rx-java rx-java2 mockk