【问题标题】:Testing if a block is executed with OCMock测试一个块是否使用 OCMock 执行
【发布时间】:2015-03-19 07:51:12
【问题描述】:

我正在使用OCMockXCTest 来测试一个将块作为参数的方法。我想测试该块是否在成功和失败时都执行。下面的代码是否足以测试该块已被执行?

__block  BOOL didExecute = NO;

[testSubject performActionWithBlock:^(id result, NSError *error) {
    didExecute = YES;
}];

XCTAssertTrue(didExecute);

【问题讨论】:

    标签: objective-c unit-testing objective-c-blocks xctest ocmock


    【解决方案1】:

    如果你想检查一个块是否已经被执行,Xcode 6 中最好的方法是使用XCTestExpectation

    // Create an expectation with whatever description you want
    // The description will be displayed in the test report if the expectation causes the test to fail
    XCTestExpectation *blockExpectation = [self expectationWithDescription:@"Block Expectation"];
    
    [testSubject performActionWithBlock:^(id result, NSError *error) {
        // Inside the block, fulfill the expectation
        [blockExpectation fulfill];
    }];
    
    // The timeout should be the max amount of time you want the test to wait
    [self waitForExpectationsWithTimeout:1.0 handler:nil];
    

    【讨论】:

    • 完美!我没有意识到这是在 Xcode 6 中引入的。
    猜你喜欢
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多