苹果在Xcode 6的发布说明中表示,我们现在可以直接使用XCTest进行异步测试。
有人知道如何使用Xcode 6 Beta 3(使用Objective-C或Swift)进行异步测试吗?我不想使用已知的信号量方法,而是想使用新的苹果方式。
我搜索了发布说明等内容,但什么也没找到。XCTest标头也不是很明确。
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);
}
}];
}
这个会议的视频非常完美,基本上你想做的就是这样。
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)
}
会话 414 涵盖了 Xcode6 中的异步测试。
let expectation = self.expectationWithDescription("get result bla bla")
responseThatIGotFromAsyncRequest = response.result.value
expectation.fulfill()
waitForExpectationsWithTimeout(10)
步骤4:在异步调用完成后进行断言
XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)