XCTest Assert Expectation没有实现

Phi*_*tin 5 xcode ios xctest xctestexpectation

当使用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);
        }
    }];
}
Run Code Online (Sandbox Code Playgroud)

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

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

小智 9

我知道这已经有几年了,但我偶然发现XCTestExpectation上的一个参数让你反转了期望值.希望这将有助于其他人绊倒这个.答案是在Swift中

let expectation = XCTestExpectation(description: "")
expectation.isInverted = true
Run Code Online (Sandbox Code Playgroud)

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


Ric*_*tos 2

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

- (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);
}
Run Code Online (Sandbox Code Playgroud)