【问题标题】:XCTest Assert Expectation wasn't fulfilledXCTest 断言期望未满足
【发布时间】:2016-05-27 01:48:46
【问题描述】:

当使用 XCTest 和 XCTestExpectation 编写某个异步测试时,我想断言某个块执行。以下代码成功断言块已执行,否则测试失败。

#import <XCTest/XCTest.h>
#import "Example.h"

@interface Example_Test : XCTestCase

@property (nonatomic) Example *example;

@end

@implementation Example_Test
- (void)setUp {
    [super setUp];
}

- (void)tearDown {
     [super tearDown];
}

- (void)testExampleWithCompletion {
    self.example = [[Example alloc] init];
    XCTestExpectation *expectation = [self expectationWithDescription:@"expection needs to be fulfilled"];
    [self.example exampleWithCompletion:^{
        [expectation fulfill]
    }];
    [self waitForExpectationsWithTimeout:2.0 handler:^(NSError *error) {
        if (error) {
            NSLog(@"Timeout Error: %@", error);
        }
    }];
}

似乎没有一种明显的方法可以反过来执行此操作;如果块在超时后未执行,则测试成功,如果在超时之前执行,则测试失败。除此之外,我想断言该块在满足不同条件时稍后执行。

是否有一种直接的方法可以使用 XCTestExpectation 执行此操作,还是我必须创建一个解决方法?

【问题讨论】:

    标签: ios xcode xctest xctestexpectation


    【解决方案1】:

    我知道这已经有几年的历史了,但我只是偶然发现了 XCTestExpectation 上的一个参数,它可以让你反转期望。希望这将帮助其他人偶然发现这一点。答案在 Swift 中

    let expectation = XCTestExpectation(description: "")
    expectation.isInverted = true
    

    文档:https://developer.apple.com/documentation/xctest/xctestexpectation/2806573-isinverted

    【讨论】:

      【解决方案2】:

      您可以通过安排在超时前运行的dispatch_after 调用来实现此目的。使用BOOL 记录块是否已执行,并在预期完成后使用断言通过或失败测试。

      - (void)testExampleWithCompletion {
          self.example = [[Example alloc] init];
          __block BOOL completed = NO;
          [self.example exampleWithCompletion:^{
              completed = YES;
          }];
      
          XCTestExpectation *expectation = [self expectationWithDescription:@"expection needs to be fulfilled"];
          dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              [expectation fulfill];
          });
          [self waitForExpectationsWithTimeout:3.0 handler:nil];
      
          XCTAssertEqual(completed, NO);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        • 2015-02-19
        相关资源
        最近更新 更多