【问题标题】:XCTest passes when it should fail using expectationsXCTest 在使用期望失败时通过
【发布时间】:2015-06-04 15:43:19
【问题描述】:

我正在测试一种在后台运行并在完成时执行代码块的方法。我正在使用期望来处理测试的异步执行。我写了一个简单的测试来显示行为:

- (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(@"fail test"); 行在此测试中应该失败,但测试通过了。

我还注意到,这只发生在代码在回调上运行需要一定时间时(在我的例子中,我正在检查文件系统上的一些文件)。这就是为什么usleep(50); 行是重现该案例所必需的原因。

【问题讨论】:

    标签: objective-c xcode xctest xctestexpectation


    【解决方案1】:

    backgroundMethodWithCallback 调用的块立即满足预期,从而让测试在调用XCTFail 之前完成。如果该块在完成执行其他操作之前满足了期望,那么您最终会遇到竞争条件,其中测试的行为取决于执行该块的其余部分的速度。但是,如果测试本身已经完成,则不应期望捕获XCTFail

    底线,如果您将[expectation fulfill] 移动到块的末尾,则此竞争条件将被消除。

    【讨论】:

      【解决方案2】:

      必须在所有测试检查后实现预期。将行移到回调块的末尾足以使测试失败:

      - (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 guides 中,fulfill 消息是在块的末尾发送的,这很有意义。

      注意:我首先在 swift 中找到了an example,其中fulfill 方法在回调开始时被调用。我不知道是示例不正确还是与Objective-C有区别。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-11
        • 1970-01-01
        • 2021-12-31
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多