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

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);
}
于 2016-03-09T04:49:22.373 に答える