kin*_*trV 1 closures unit-testing swift
有些功能可以向服务器发送请求,获取响应和打印结果.他们总是在IOS应用程序本身工作,但有时只在这个应用程序的单元测试中(看起来像随机).
主要问题:xcode不会在单元测试中进入闭包体,只是跳过它.
任何想法如何解决? 在此输入图像描述
最可能的原因是因为请求的完成关闭没有被完成,因为它们正在执行异步操作,而测试同步运行.这意味着当您的网络请求仍在处理时,测试将完成运行.
尝试使用XCTestExpectation:
func testIt() {
let expectation = expectationWithDescription("foobar")
// request setup code here...
Alamofire.request(.POST, "...")
.responseJSON { response in
//
// Insert the test assertions here, for example:
//
if let JSON = response.result.value as? [String: AnyObject] {
XCTAssertEqual(JSON["id"], "1")
} else {
XCTFail("Unexpected response")
}
//
// Remember to call this at the end of the closure
//
expectation.fulfill()
}
//
// This will make XCTest wait for up to 10 seconds,
// giving your request expectation time to fulfill
//
waitForExpectationsWithTimeout(10) { error
if let error = error {
XCTFail("Error: \(error.localizedDescription)")
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1971 次 |
| 最近记录: |