10

当使用 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 执行此操作,或者我必须创建一个解决方法?

4

2 回答 2

19

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

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

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

于 2018-04-14T20:18:51.973 回答
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);
}
于 2016-03-09T04:49:22.373 回答