objective-c – XCTest在使用期望失败时通过

前端之家收集整理的这篇文章主要介绍了objective-c – XCTest在使用期望失败时通过前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在测试一个在后台运行的方法,并在完成后执行代码块.我正在使用期望来处理测试的异步执行.我写了一个简单的测试来显示行为:

- (void) backgroundMethodWithCallback: (void(^)(void)) callback {
    dispatch_queue_t backgroundQueue;
    backgroundQueue = dispatch_queue_create("background.queue",NULL);
    dispatch_async(backgroundQueue,^(void) {
        callback();
    });
}

- (void) testMethodWithCallback {
    XCTestExpectation *expectation = [self expectationWithDescription:@"Add collection bundle"];
    [self backgroundMethodWithCallback:^{
        [expectation fulfill];

        usleep(50);
        XCTFail(@"fail test");
    }];
    [self waitForExpectationsWithTimeout: 2 handler:^(NSError *error) {
        if (error != nil) {
            XCTFail(@"timeout");
        }
    }];
}

XCTFail(@“失败测试”);对于此测试,该行应该失败,但测试正在通过.

我还注意到,这只发生在回调上运行的代码需要一段时间(在我的情况下,我正在检查文件系统上的一些文件).这就是为什么usleep(50);线条是重现案件的必要条件.

解决方法

所有测试检查后必须满足期望.将行移动到回调块的末尾足以使测试失败:

- (void) testMethodWithCallback {
    XCTestExpectation *expectation = [self expectationWithDescription:@"Add collection bundle"];
    [self backgroundMethodWithCallback:^{

        usleep(50);
        XCTFail(@"fail test");
        [expectation fulfill];
    }];
    [self waitForExpectationsWithTimeout: 2 handler:^(NSError *error) {
        if (error != nil) {
            XCTFail(@"timeout");
        }
    }];
}

我没有找到关于此的明确文档,但是在apple developer guide中,完成消息是在块结束时发送的,这很有意义.

注意:我首先在swift中找到了an example,其中在回调开始时调用了fulfill方法.我不知道的是,如果示例不正确或者与Objective-C存在差异.

猜你在找的Xcode相关文章