【问题标题】:Firebase and Swift 3 Asynchronous Unit TestingFirebase 和 Swift 3 异步单元测试
【发布时间】:2017-04-26 18:15:02
【问题描述】:

所以我在网上做了一些研究,我发现的最佳答案要么已过时,要么适用于 Android。任何帮助表示赞赏!

对于我上周完成的另一个项目,我必须为使用 Swift 2.3 的自定义 Heroku/PostGreSQL 后端编写大约 2 打测试用例。我所做的只是在测试开始时创建一个 asyncExpectation 变量,在完成处理程序执行后实现期望,然后在测试的底部等待它实现。

现在我将 Firebase 和 Swift 3 用于一个新项目。出于某种原因,当我取消注释下面的 asyncExpectation.fulfill() 时,没有任何内容添加到数据库中。将其注释掉后,一切正常。我应该如何使用 Firebase 和 Swift 3 测试数据存储/检索?

编辑:我应该在我的在线研究中包括这一点,我发现我可能需要使用调度,但这似乎是嵌套完成处理程序的解决方案,而我的数据库append 方法不是一个完成处理程序,所以我我不知道如何进行。

class RooMate_v2Tests: XCTestCase {
    func testCreateUser() {

        let asyncExpectation = expectation(description: "createUserTestOne")
        var testSuccess = false

        let testUser = (email: "TESTUSER|" + String().randomString(length: 6) + "@test.com", password: String().randomString(length: 6), firstName: "jimmy", lastName: "jenkins")

        FIRAuth.auth()?.createUser(withEmail: testUser.email, password: testUser.password) { (user, error) in
            if error != nil {
            print("Error: \(error.debugDescription)")
            } else {
            let userProfileInfo = ["firstName" : testUser.firstName,
                                   "lastName" : testUser.lastName,
                                   "email" : testUser.email,
                                   "profilePictureURL" : "N/A"]

                let backendRef = FIRDatabase.database().reference()                
                backendRef.child("users").child("TESTUSER|" + user!.uid).setValue(userProfileInfo)
                // testSuccess = true
            }
            // asyncExpectation.fulfill()
        }

        waitForExpectations(timeout: 10) { (error) in
            XCTAssertTrue(testSuccess)
        }
    }
}

【问题讨论】:

  • 您是否尝试设置更高的超时时间?
  • 是的,我试过了。超时似乎不是问题。不过这是一个很好的建议,因为这可以解释为什么删除 expect.fulfill() 会使它起作用。我已经做到了 30 秒,但它仍然无法正常工作。当我删除履行时,只需约 5 秒即可将数据添加到后端。
  • 你看我的回答了吗?对吗?

标签: ios swift firebase swift3 firebase-authentication


【解决方案1】:

在我看来,您的问题是您正在等待处理程序中检查 setValue 是否成功。如文档中所述,只有在超时的情况下才会调用处理程序

调用时要调用的块 -waitForExpectationsWithTimeout:handler: 超时或已满足所有相关的期望。

我建议你检索刚刚设置的值并检查它,如下所示:

let retrievedUserProfile = backendRef.child("users").child("TESTUSER|" + user!.uid)
XCTAssertTrue(retrievedUserProfile == userProfileInfo)

我不知道这段代码是否正确,只是为了解释我的建议。
希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-15
    • 2020-07-14
    • 2012-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多