2016-02-16 64 views
2

當使用XCTest和XCTestExpectation編寫某個異步測試時,我想聲明某個塊是而不是執行。下面的代碼在聲明塊已執行並且如果不是測試失敗時成功。XCTest聲明期望沒有履行

#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或我將不得不建立一個解決方法?

回答

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); 
}