加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-14 17:46:43 所属栏目:百科 来源:网络整理
导读:我正在测试一个在后台运行的方法,并在完成后执行代码块.我正在使用期望来处理测试的异步执行.我写了一个简单的测试来显示行为: - (void) backgroundMethodWithCallback: (void(^)(void)) callback { dispatch_queue_t backgroundQueue; backgroundQueue = d
我正在测试一个在后台运行的方法,并在完成后执行代码块.我正在使用期望来处理测试的异步执行.我写了一个简单的测试来显示行为:

- (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存在差异.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读