Xcode中的XCTest和异步测试

时间:2014-07-11 18:37:20

标签: ios xcode xctest

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

任何人都知道如何使用Xcode 6 Beta 3(使用Objective-C或Swift)?我不想要已知的信号量方法,但需要新的Apple方式。

我搜索了发布的笔记以及更多,但我什么也没找到。 XCTest标头也不是非常明确。

4 个答案:

答案 0 :(得分:65)

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

    }];
}

答案 1 :(得分: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)
}

答案 2 :(得分:11)

会话414涵盖Xcode6中的异步测试

https://developer.apple.com/videos/wwdc/2014/#414

答案 3 :(得分:1)

How I did in swift2

Step 1: define expectation

let expectation = self.expectationWithDescription("get result bla bla")

Step 2: tell the test to fulfill expectation right below where you capture response

responseThatIGotFromAsyncRequest = response.result.value
expectation.fulfill()

Step 3: Tell the test to wait till the expectation is fulfilled

waitForExpectationsWithTimeout(10)

STep 4: make assertion after async call is finished

XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)