【发布时间】:2014-09-02 11:15:32
【问题描述】:
Apple 在 Xcode 6 的发行说明中表示,我们现在可以直接使用 XCTest 进行异步测试。
任何人都知道如何使用 Xcode 6 Beta 3(使用 Objective-C 或 Swift)来做到这一点?我不想要已知的信号量方法,而是新的 Apple 方式。
我搜索了已发布的说明等,但一无所获。 XCTest 标头也不是很明确。
【问题讨论】:
Apple 在 Xcode 6 的发行说明中表示,我们现在可以直接使用 XCTest 进行异步测试。
任何人都知道如何使用 Xcode 6 Beta 3(使用 Objective-C 或 Swift)来做到这一点?我不想要已知的信号量方法,而是新的 Apple 方式。
我搜索了已发布的说明等,但一无所获。 XCTest 标头也不是很明确。
【问题讨论】:
会议视频很完美,基本上你想做这样的事情
func testFetchNews() {
let expectation = self.expectationWithDescription("fetch posts")
Post.fetch(.Top, completion: {(posts: [Post]!, error: Fetcher.ResponseError!) in
XCTAssert(true, "Pass")
expectation.fulfill()
})
self.waitForExpectationsWithTimeout(5.0, handler: nil)
}
【讨论】:
我在 swift2 中的表现如何
第 1 步:定义期望
let expectation = self.expectationWithDescription("get result bla bla")
第 2 步:告诉测试在您捕获响应的正下方满足期望
responseThatIGotFromAsyncRequest = response.result.value
expectation.fulfill()
第 3 步:告诉测试等到期望得到满足
waitForExpectationsWithTimeout(10)
步骤 4:异步调用完成后进行断言
XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)
【讨论】:
Obj-C 示例:
- (void)testAsyncMethod
{
//Expectation
XCTestExpectation *expectation = [self expectationWithDescription:@"Testing Async Method Works!"];
[MyClass asyncMethodWithCompletionBlock:^(NSError *error, NSHTTPURLResponse *httpResponse, NSData *data) {
if(error)
{
NSLog(@"error is: %@", error);
}else{
NSInteger statusCode = [httpResponse statusCode];
XCTAssertEqual(statusCode, 200);
[expectation fulfill];
}
}];
[self waitForExpectationsWithTimeout:5.0 handler:^(NSError *error) {
if(error)
{
XCTFail(@"Expectation Failed with error: %@", error);
}
}];
}
【讨论】:
asyncMethod 没有完成块怎么办?我不知道如何测试。
Session 414 涵盖了 Xcode6 中的异步测试
【讨论】: