[英]MockK Coroutine Response Fails to Answer
Trying to dig deeper into using MockK
where a coroutine is involved.试图深入挖掘在涉及协程的情况下使用MockK
。 I have this test:我有这个测试:
class UserDataUseCaseTest {
@MockK
val dataFetcherService: DataFetcherService = mockk()
@MockK
val userData: UserData = mockk()
@ExperimentalCoroutinesApi
@Test
fun `fetching salt populates user data salt value`() = runBlockingTest {
MockKAnnotations.init(this)
val userDataUseCase = UserDataUseCase(mockk(), mockk(), mockk())
every { userData.user_name } returns FAKE_USER
coEvery { dataFetcherService.getSaltForUser(FAKE_USER) } returns SALT_RESPONSE
userDataUseCase.getSaltForUser(userData)
assertEquals(SALT, userData.salt)
}
companion object {
private const val FAKE_USER = "fake_user"
private const val SALT = "salt"
private val SALT_RESPONSE = SaltResponse(
result = "",
title = "",
message = "",
salt = SALT,
auth_code = "auth_code",
userMustChangePassword = false
)
}
}
This fails with the following error:这失败并出现以下错误:
io.mockk.MockKException: no answer found for: DataFetcherService(#4).getSaltForUser(fake_user, continuation {}) io.mockk.MockKException:找不到答案:DataFetcherService(#4).getSaltForUser(fake_user, continuation {})
The method that I am trying to test looks like this:我尝试测试的方法如下所示:
@VisibleForTesting
suspend fun getSaltForUser(userData: UserData) {
val saltResponse = dataFetcherService.getSaltForUser(userData.user_name)
with (userData) {
salt = if (saltResponse.salt.isEmpty())
KeyChainWrapper().generateRandomString(KeyChainWrapper.SALT_LEN)
else saltResponse.salt
authCode = saltResponse.auth_code
userMustChangePassword = saltResponse.userMustChangePassword
}
}
Why am I not getting an answer for the getSaltForUser()
call?为什么我没有得到getSaltForUser()
调用的答案? Thanks for any help.谢谢你的帮助。
From the look of that sample code the class under test is not using the same mock as the one defined in the test:从该示例代码的外观来看,被测 class 没有使用与测试中定义的相同的模拟:
val userDataUseCase = UserDataUseCase(mockk(), mockk(), mockk())
should be something like应该是这样的
val userDataUseCase = UserDataUseCase(dataFetcherService, mockk(), mockk())
depending on which parameter the DataFetcherService
should be取决于DataFetcherService
应该是哪个参数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.