Testing asynchronous call in unit test in iOS

后端 未结 12 1538
-上瘾入骨i
-上瘾入骨i 2020-12-24 08:51

I am facing a problem while unit testing an asynchronous call in iOS. (Although it is working fine in view controllers.)

Has anyone faced this issue before? I have t

12条回答
  •  无人及你
    2020-12-24 09:44

    Here is Apple's description of native support for async testing.

    TL;DR manual:

    Look at XCTextCase+AsynchronousTesting.h

    There is special class XCTestExpectation with only one public method: - (void)fulfill;

    You should init instance of this class and in success case call fulfill method. Otherwise your test will fail after timeout that you specify in that method:

    - (void)waitForExpectationsWithTimeout:(NSTimeInterval)timeout handler:(XCWaitCompletionHandler)handlerOrNil;
    

    Example:

    - (void)testAsyncMethod
    {
    
        //Expectation
        XCTestExpectation *expectation = [self expectationWithDescription:@"Testing Async Method Works Correctly!"];
    
        [MyClass asyncMethodWithCompletionBlock:^(NSError *error) {        
            if(error)
                NSLog(@"error is: %@", error);
            else
                [expectation fulfill];
        }];
    
        //Wait 1 second for fulfill method called, otherwise fail:    
        [self waitForExpectationsWithTimeout:1 handler:^(NSError *error) {
    
            if(error)
            {
                XCTFail(@"Expectation Failed with error: %@", error);
            }
    
        }];
    }
    

提交回复
热议问题