我为我的App实现了我的第一个测试用例。在每个测试用例之前,我需要使用Firebase登录。
我使用Tasks API编写了Firebase类中的所有内容。 Firebase类是异步的但发回一个Task,结果可以使用addOnCompleteListener读取。但是,登录后,logUserIn(),测试停止,“someNumber”无法打印。我不能将logUserIn()方法放在@Before方法中,因为它是异步的。
@RunWith(AndroidJUnit4::class)
class NetworthServiceTest {
@Rule
@JvmField
val rule = ActivityTestRule(MainActivity::class.java)
private fun logUserIn(): Task<Boolean> {
val tcs = TaskCompletionSource<Boolean>()
val task = FirebaseService().initialize(
TEST_USER_EMAIL,
TEST_USER_PASSWORD,
rule.activity)
task.addOnCompleteListener {
Assert.assertEquals("User " + TEST_USER_EMAIL + " cannot be logged in", "", it.result.second)
val loginManager = UtilsProvider().getBookyLoginManager()
Assert.assertEquals("User should be logged in", true, loginManager.isLoggedIn())
tcs.setResult(true)
}
return tcs.task
}
@Test
@Throws(Exception::class)
fun whenReadingTableShouldGive10Results() {
val task = logUserIn()
task.addOnCompleteListener {
val someNumber = 10
Log.d("","print nr = "+ someNumber)
}
}
}
class FirebaseService {
fun initialize(email: String, password: String, activity: Activity): Task<Pair<Any, String>> {
database = FirebaseDatabase.getInstance().reference
auth = FirebaseAuth.getInstance()
val tcs = TaskCompletionSource<Pair<Any, String>>()
auth!!.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(activity) { task ->
if (task.isSuccessful) {
user = auth!!.currentUser
isInitialized = true
val pair = Pair<Any, String>(null, "")
tcs.setResult(pair)
} else {
val pair = Pair<Any, String>(null, "error: " + task.exception!!.message)
tcs.setResult(pair)
}
}
return tcs.task
}
}
答案 0 :(得分:1)
您可以use Tasks.await() to block the current thread等待任务完成。对于应用程序代码,我们不建议这样做(请参阅this blog中的更多内容),但测试应该没问题。