【问题标题】:API Violation - Multiple calls made in Swift 4API 违规 - 在 Swift 4 中进行多次调用
【发布时间】:2018-09-26 05:42:04
【问题描述】:

尝试对网络调用进行单元测试并收到以下错误:

API violation - multiple calls made to -[XCTestExpectation fulfill]

如果以前写过这种风格的测试,但这个似乎是在创造错误,我似乎无法弄清楚为什么。

func testAccessKeys() {
    let expected = expectation(description: "Run the Access request")
    sut.request(.Access, data: nil) { finished, response in
        if response != nil && finished == true {
            if let json = response as? [String:Any] {
                if json["id"] as? String != nil, json["secret"] as? String != nil {
                    XCTAssertNotNil(json)
                    expected.fulfill()
                } else {
                    XCTFail("Access response was not in correct format")
                    expected.fulfill()
                }
            } else {
                XCTFail("Access request was not a dictionary")
                expected.fulfill()
            }
        } else {
            XCTFail("Access response was nil")
            expected.fulfill()
        }
    }
    waitForExpectations(timeout: 3) { error in
        if let error = error {
            XCTFail("Access request failure: \(error.localizedDescription)")
        }
    }

}

更新 简化调用解决了问题:

func testAccessKeys() {
    let expected = expectation(description: "Run the Access request")
    sut.request(.Access, data: nil) { finished, response in
        if response != nil && finished == true {
            if let json = response as? [String:Any] {
                if json["id"] as? String != nil, json["secret"] as? String != nil {
                    print("ID: \(String(describing: json["id"]))")
                    print("Secret: \(String(describing: json["secret"]))")
                    expected.fulfill()
                } else {
                    XCTFail("Access response was not in correct format")
                }
            } else {
                XCTFail("Access request was not a dictionary")
            }
        } else {
            XCTFail("Access response was nil")
        }
    }
    waitForExpectations(timeout: 3, handler: nil)
}

【问题讨论】:

  • Google 第一次点击的答案将我带到this,这似乎是异步操作多次调用completionHandler 的问题。可能sut.request 正在做类似的事情?
  • sut.request 只被调用一次。控制台确认了这一点。
  • 是的,但它有什么作用?您可以调用sut.request 一次,但该方法可以多次调用completionHandler(finished, response)。同样,您最好在代码中添加一些手动断点并尝试。
  • Sut.request 是标准 Alamofire.request 调用的包装器。
  • 您应该调用expected.fulfill() 作为完成处理程序的最后一行。也许你应该检查finished == true,但如果它只被调用一次,就像你说的那样,那么就没有必要了。

标签: ios swift unit-testing


【解决方案1】:

我遇到了类似的问题。我通过确保只调用一次 expectation.fulfill() 来解决它。如果您有多个期望,请确保您的期望有不同的描述。例如:self.expectation(description: "expected description")
多次调用它会导致崩溃。
在我的情况下,我有一个依赖于另一个测试用例的测试用例。那里的期望不止一次被调用。我通过将其设置为单个来解决它
您本可以发布您的 UPDATE 作为答案!

【讨论】:

    猜你喜欢
    • 2015-03-27
    • 2014-09-29
    • 2018-11-06
    • 2018-05-21
    • 2014-08-10
    • 2021-02-26
    • 2021-12-06
    • 2014-08-28
    • 1970-01-01
    相关资源
    最近更新 更多