提问人:Bob Redity 提问时间:4/12/2021 更新时间:3/24/2023 访问量:440
如何模拟task.isSuccessful google.android.gms.tasks?
How to mock task.isSuccessful google.android.gms.tasks?
问:
需要模拟响应,但由于某种原因无法正确导入。那么如何嘲笑它
package com.google.android.gms.tasks;
public abstract class Task<TResult> {
public Task() {
}
public abstract boolean isComplete();
public abstract boolean isSuccessful();
答:
0赞
Daniel Jonker
3/24/2023
#1
不是 100% 确定我是否理解您的问题。但是,如果您尝试包装使用 firebase 任务的内容(例如远程配置),则可能需要自己实现 Task。例如:
override fun loadConfig(onSuccess: () -> Unit, onFailure: () -> Unit) {
firebaseRemoteConfig.fetchAndActivate().addOnCompleteListener() { task ->
if (task.isSuccessful) {
onSuccess()
} else {
onFailure()
}
}
}
然后,为了测试它,您必须创建自己的 Task 实现,而不是使用像这样的模拟:
class TestTask(private val isSuccess: Boolean) : Task<Boolean>() {
override fun addOnFailureListener(p0: OnFailureListener): Task<Boolean> {
TODO("Not yet implemented")
}
....
override fun addOnCompleteListener(p0: OnCompleteListener<Boolean>): Task<Boolean> {
p0.onComplete(this)
return TestTask(isSuccess)
}
override fun addOnCompleteListener(
p0: Activity,
p1: OnCompleteListener<Boolean>
): Task<Boolean> {
TODO("Not yet implemented")
}
...
override fun isSuccessful(): Boolean {
return this.isSuccess
}
}
然后,您可以调用远程配置来测试您的类,如下所示:
@Test
fun `should return success callback when successfully loading config`() {
every { firebaseRemoteConfig.fetchAndActivate() } returns TestTask(true)
var testReachedCallbackBlock = false
testSubject.loadConfig(
onSuccess = {
testReachedCallbackBlock = true
},
onFailure = {}
)
assertTrue(testReachedCallbackBlock)
}
评论