当使用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上的一个参数让你反转了期望值.希望这将有助于其他人绊倒这个.答案是在Swift中
let expectation = XCTestExpectation(description: "") expectation.isInverted = true
文档:https://developer.apple.com/documentation/xctest/xctestexpectation/2806573-isinverted