You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SwiftUI UI测试调用waitForExpectations测试Firebase手机号认证崩溃如何解决

崩溃原因

XCTest 中的 waitForExpectations(timeout:handler:) 是同步阻塞API,同一时间同一个测试用例实例只能运行一个 waitForExpectations 调用。你的代码在第一个发送OTP的异步回调里,刚调用完expection.fulfill()就立刻触发了testVerifyOTP方法,此时第一个waitForExpectations的执行流程还没有完全结束,第二个方法里又发起了新的waitForExpectations调用,因此触发了API违规的崩溃报错。

修复方案

推荐将两个验证步骤合并到同一个测试方法内,等第一个waitForExpectations完全执行完成后,再执行第二个验证逻辑,示例代码如下:

func testsendOTPAndVerify() {
    // 第一步:等待OTP发送成功
    let sendOTPExpectation = expectation(description: "OTP Send With Correct Number")
    var receivedVerificationId: String?
    
    let signupClassMthd = SignupScreen(phoneNumber: .constant("9814012345"))
    signupClassMthd.verify { response, verificationId in
        XCTAssertTrue(response)
        if response {
            receivedVerificationId = verificationId
            sendOTPExpectation.fulfill()
        }
    }
    waitForExpectations(timeout: 30) { error in
        if let error = error {
            print("OTP Send ", error.localizedDescription)
        }
    }
    
    // OTP发送失败直接终止测试
    guard let verificationID = receivedVerificationId else {
        XCTFail("获取verificationId失败,无法继续验证OTP")
        return
    }
    
    // 第二步:等待OTP验证完成
    let verifyOTPExpectation = expectation(description: "Check OTP")
    let verfyClassTest = VerficationCode(phoneNumber: .constant(CommonAllString.BlankStr), verificationID: .constant(verificationID))
    verfyClassTest.verifyPhoneNumberAndLogin(OtpEndrdCode: "000000") { response, responseBool in
        XCTAssertTrue(response && !responseBool)
        if response && !responseBool {
            verifyOTPExpectation.fulfill()
        }
    }
    waitForExpectations(timeout: 30) { error in
        if let error = error {
            print("Check OTP = ", error.localizedDescription)
        }
    }
}

修改后两个waitForExpectations是顺序执行,不会出现同时等待的冲突,即可解决崩溃问题。

内容的提问来源于stack exchange,提问作者Sham Dhiman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 11:45:03