【问题标题】:XCTest and asynchronous testing in Xcode 6Xcode 6 中的 XCTest 和异步测试
【发布时间】:2014-09-02 11:15:32
【问题描述】:

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

任何人都知道如何使用 Xcode 6 Beta 3(使用 Objective-C 或 Swift)来做到这一点?我不想要已知的信号量方法,而是新的 Apple 方式。

我搜索了已发布的说明等,但一无所获。 XCTest 标头也不是很明确。

【问题讨论】:

    标签: ios xcode xctest


    【解决方案1】:

    会议视频很完美,基本上你想做这样的事情

    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】:

      我在 swift2 中的表现如何

      第 1 步:定义期望

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

      第 2 步:告诉测试在您捕获响应的正下方满足期望

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

      第 3 步:告诉测试等到期望得到满足

      waitForExpectationsWithTimeout(10)
      

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

      XCTAssertEqual(responseThatIGotFromAsyncRequest, expectedResponse)
      

      【讨论】:

        【解决方案3】:

        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 没有完成块怎么办?我不知道如何测试。
        • 假设您在 dispatch_queue 上运行它,您可以在开始计划执行的工作后将测试安排在同一个队列上。只需将 dispatch_async 放到同一个队列中,然后在该延续块中执行您需要的操作
        【解决方案4】:

        Session 414 涵盖了 Xcode6 中的异步测试

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

        【讨论】:

        • 为了更容易在列表中找到:此会话名为“Testing in Xcode 6”。
        猜你喜欢
        • 1970-01-01
        • 2015-01-30
        • 2021-11-16
        • 2014-08-30
        • 1970-01-01
        • 1970-01-01
        • 2014-11-30
        • 2016-02-19
        • 2015-06-14
        相关资源
        最近更新 更多