在 espresso 测试用例中创建新的 Firebase 用户时从未调用过 OnCompleteListener

OnCompleteListener never called while creating new Firebase user in espresso test case

对于集成测试,我想用一个新创建的用户帐户做一些测试。为此,我在我的测试用例函数中创建了一个 Firebase 用户,如下所示:

    @Test
    fun registerAndSigningInWithVeryNewUser() {
        val auth = Firebase.auth
        auth.createUserWithEmailAndPassword(strEmail, strPassword)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success")
                    // doing some test stuff
                } else {
                    // If sign in fails
                    Log.w(TAG, "createUserWithEmail:failure", task.exception)
                    assert(false)
                }
            }
    }

新用户帐户已正确创建。我可以在 Firebase 身份验证仪表板中验证这一点。但是 addOnCompleteListener 中的 task 永远不会被调用。我不明白为什么。

更新:如果我使用调试器并逐步通过测试功能,则会调用侦听器。所以我想我需要一些空闲代码来等待异步数据库调用

有什么提示吗?

问题是,被调用的函数是对远程服务器的异步调用(当然)。

测试用例在响应到达之前结束。所以我添加了一个丑陋的 Thread.sleep(10000).

    @Test
    fun registerAndSigningInWithVeryNewUser() {
        val auth = Firebase.auth
        auth.createUserWithEmailAndPassword(strEmail, strPassword)
            .addOnCompleteListener { task ->
                if (task.isSuccessful) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d(TAG, "createUserWithEmail:success")
                    // doing some test stuff
                } else {
                    // If sign in fails
                    Log.w(TAG, "createUserWithEmail:failure", task.exception)
                    assert(false)
                }
            }
            Thread.sleep(10000)
    }

但使用 Thread.sleep(...) 并不总是好的:https://www.repeato.app/android-espresso-why-to-avoid-thread-sleep/ ore https://developer.android.com/training/testing/espresso/idling-resource