如何解决在Android单元测试中模拟挂起的函数调用
我有一个要测试的函数withCredentials
,该函数用于传递使用用户凭据进行API调用所需的必需参数,它看起来像这样:
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal suspend fun <T> withCredentials(block: suspend (String) -> Response<T>): ServiceResponse<T>
它的责任是填写身份验证载体(传递的块中的字符串)进行api调用,并生成ServiceResponse对象(基本上是与实际响应合并的响应对象)并返回结果,从不抛出例外
它被这样称呼:
val response = withCredentials{ bearer -> service.logIn(bearer,userName,password) }
我希望测试withCredentials方法而无需测试特定方案(例如,在登录过程中会调用上面的情况)
我目前正在做的事情是这样的:
fun `test with credentials is calls nothing when there are no credentials saved`() {
runBlocking {
whenever(prefs.auth).thenReturn(null)
val response = withCredentials(this@CoreTests::testSuccess)
assertEquals(0,called)
}
}
private var called = 0
private suspend fun testSuccess(bearer: String?): Response<String> {
delay(1)
called++
return Response.success(200,"$bearer test")
}
为了验证(在此示例中)在没有保存凭据的情况下永远不会调用testSuccess
private val functionCall = mock(suspend (String?)-> ServiceResponse<String>) //this is ofc incorrect I need the correct code here
fun `test with credentials is calls nothing when there are no credentials saved`() {
runBlocking {
whenever(prefs.auth).thenReturn(null)
val response = withCredentials(this@CoreTests::testSuccess)
verify(functionCall,never()).invoke(any())
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。