【问题标题】:iOS9 XCTest - how to use expectations to test asynchronous cases without blocks?iOS9 XCTest - 如何使用期望来测试没有阻塞的异步案例?
【发布时间】:2016-04-17 15:26:54
【问题描述】:

我正在查看this example of using asynchronous testing using iOS9 expectations。这对于网络请求和其他具有可以满足预期的完成块的操作是有意义的。

但是,我正在尝试对不使用回调块的类进行单元测试。到目前为止,我发现下面的代码在某些时候有效,但我不确定我是否使用了正确的方法。

如何在应用有机会在后台执行某些操作时延迟测试用例?在这种情况下我可以使用执行选择器来检查某些内容并在超时之前满足该后台线程的期望?

-(void)checkFoundExpectedSubview:(MockViewController*)mockViewController
{
    if(mockViewController.didFindExpectedSubview)
    {
        [self.expectation fulfill];
    }
}


-(void)testErrorMessage
{
    MockViewController* mockViewController = [MockViewController create];
    [mockViewController expectSubviewWithClass:@"TSMessageView"];

    NSString* title = @"Error!";
    NSString* subtitle = @"This is a unit test of an error message";

    [self.errorHandler reportErrorWithTitle:title message:subtitle];
//this checks and fulfills my expectation
    [self performSelector:@selector(checkFoundExpectedSubview:) withObject:mockViewController afterDelay:2];

    self.expectation = [self expectationWithDescription:@"Waiting for the error to be presented"];

    [self waitForExpectationsWithTimeout:3 handler:^(NSError * _Nullable error) {
        XCTAssertNil(error);
    }];
}

【问题讨论】:

    标签: objective-c unit-testing ios9 xctest xctestexpectation


    【解决方案1】:

    您可以使用CFRunLoopRunInMode()等待一定的时间,或者直到条件满足。

    time_t start = time(NULL);
    while (![mockViewController checkFoundExpectedSubview] && time(NULL)-start < 5.0) {
        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.1, NO);
    }
    XCTAssertTrue([mockViewController checkFoundExpectedSubview], "Expected something, didn't happen");
    

    上面的代码将一直等待,直到checkFoundExpectedSubview 返回 true,或者允许的 5 秒持续时间过去。让运行循环运行意味着允许主线程(队列)处理提交给它的事件和块。

    代码可以总结成一个很好的宏:

    #define wait(timeout, condition, message) \
    { \
        time_t start = time(NULL); \
        while (!condition && time(NULL)-start < 5.0) { \
            CFRunLoopRunInMode(kCFRunLoopDefaultMode, .1, NO); \
        } \
        XCTAssertTrue(condition, message); \
    }
    

    可以这样使用:

    wait(5, [mockViewController checkFoundExpectedSubview], "Expected something, didn't happen");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2016-02-19
      • 2014-08-30
      • 1970-01-01
      • 2017-10-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多