ios XCTest 和 Xcode 6 中的异步测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24704338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
XCTest and asynchronous testing in Xcode 6
提问by Dimillian
So Apple said in the release note of Xcode 6 that we can now do asynchronous testing directly with XCTest.
所以苹果在 Xcode 6 的发布说明中说,我们现在可以直接用 XCTest 做异步测试。
Anyone knows how to do it using Xcode 6 Beta 3 (Using objective-C or Swift)? I don't want the known semaphore method, but the new Apple way.
任何人都知道如何使用 Xcode 6 Beta 3(使用 Objective-C 或 Swift)来做到这一点?我不想要已知的信号量方法,而是新的 Apple 方式。
I searched into the released note and more but I found nothing. The XCTest header is not very explicit either.
我搜索了已发布的笔记等内容,但一无所获。XCTest 标头也不是很明确。
回答by jonbauer
Obj-C example:
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);
}
}];
}
回答by Dimillian
The sessions video is perfect, basically you want to do something like this
会议视频很完美,基本上你想做这样的事情
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)
}
回答by mittens
Session 414 covers async testing in Xcode6
Session 414 涵盖了 Xcode6 中的异步测试
回答by Ankit Vij
How I did in swift2
我在 swift2 中的表现
Step 1: define expectation
第 1 步:定义期望
let expectation = self.expectationWithDescription("get result bla bla")
Step 2: tell the test to fulfill expectation right below where you capture response
第 2 步:告诉测试满足您捕获响应的下方的期望
responseThatIGotFromAsyncRequest = response.result.value
expectation.fulfill()
Step 3: Tell the test to wait till the expectation is fulfilled
第 3 步:告诉测试等待期望得到满足
waitForExpectationsWithTimeout(10)
STep 4: make assertion after async call is finished
第 4 步:在异步调用完成后进行断言
XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)