尝试对网络电话进行单元测试并收到以下错误:
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)
}
答案 0 :(得分:0)
我有类似的问题。我通过确保只expectation.fulfill()
被调用一次来解决它。如果您有多个期望,还请确保您的期望具有不同的描述。例如:self.expectation(description: "expected description"
)
多次调用它会导致崩溃。
就我而言,我有一个依赖于另一个测试用例的测试用例。在那里,期望被多次召唤。我把它做成一个了解决了
您可能已经将UPDATE发布为答案!