Xcode 6中的XCTest与异步测试

42

苹果在Xcode 6的发布说明中表示,我们现在可以直接使用XCTest进行异步测试。

有人知道如何使用Xcode 6 Beta 3(使用Objective-C或Swift)进行异步测试吗?我不想使用已知的信号量方法,而是想使用新的苹果方式。

我搜索了发布说明等内容,但什么也没找到。XCTest标头也不是很明确。

4个回答

68

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);
        }

    }];
}

5
愚蠢的问题:如果我的“asyncMethod”没有完成块怎么办?我不知道该如何测试它。 - 最白目
1
假设您在调度队列上运行它,您可以在开始计划执行的工作后,在同一队列上安排测试。只需将dispatch_async放入同一队列中,然后在该续集块中执行所需操作即可。 - Bob9630

52

这个会议的视频非常完美,基本上你想做的就是这样。

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)
}

11

为了更容易在列表中找到:此会话被命名为“在Xcode 6中进行测试”。 - Ashley

1
如何在swift2中实现:
步骤1:定义期望。
let expectation = self.expectationWithDescription("get result bla bla")

第二步:在捕获响应的下方告诉测试来满足期望。
responseThatIGotFromAsyncRequest = response.result.value
expectation.fulfill()

第三步:告诉测试等待直到期望被满足。
waitForExpectationsWithTimeout(10)

步骤4:在异步调用完成后进行断言

XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接