ios - Firebase 和 Swift 3 异步单元测试

标签 ios swift firebase swift3 firebase-authentication

因此,我在网上进行了一些研究,发现的最佳答案要么已过时,要么专为 Android 而设计。任何帮助表示赞赏!

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

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

编辑:我应该包括在我的在线研究中,我发现我可能需要使用调度,但这似乎是嵌套 completionHandlers 的解决方案,而我的数据库 append 方法并不完全一个 completionHandler,所以我不知道如何继续。

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)
        }
    }
}

最佳答案

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

A block to be invoked when a call to -waitForExpectationsWithTimeout:handler: times out or has had all associated expectations fulfilled.

我建议你检索刚刚设置的值并检查它,像这样:

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

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

关于ios - Firebase 和 Swift 3 异步单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091391/

相关文章:

ios - 为什么 XCUITest 在运行 iOS 11.0.1 的 Xcode 上失败

ios - 传输安全已阻止明文 HTTP

arrays - SWIFTUI:使用 Array 属性创建类 - 符合 'ObservableObject' 。类(class)!不是结构体

ios - 使用 UITableViewAutomaticDimension 更新 UITableViewCell 后出现抖动滚动

javascript - 如何让 For 循环等待 Firebase 数据库响应?

mobile - 使用手机数据 (3g/4g) 时无法访问 Firebase 服务器

objective-c - 如何将带有参数的 block 作为选择器传递给 performSelector :withObject:?

iOS 从相机中实时捕获视频并与音频文件混合

ios - cellForRow At IndexPath 执行一次太少?

firebase - 为什么有时imageUrl被保存在Cloud Firestore数据库中而有时却不保存