Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using XCTest, how can one chain together multiple discrete sequences of { expectations -> wait }?

The documentation for XCTest waitForExpectationsWithTimeout:handler:, states that

Only one -waitForExpectationsWithTimeout:handler: can be active at any given time, but multiple discrete sequences of { expectations -> wait } can be chained together.

However, I have no idea how to implement this, nor can I find any examples. I'm working on a class that first needs to find all available serial ports, pick the correct port and then connect to the device attached to that port. So, I'm working with at least two expectations, XCTestExpectation *expectationAllAvailablePorts and *expectationConnectedToDevice. How would I chain those two?

like image 401
Elise van Looij Avatar asked Mar 19 '15 16:03

Elise van Looij


People also ask

What is the test method to test an asynchronous operation in XCTest?

XCTest provides two approaches for testing asynchronous code. For Swift code that uses async and await for concurrency, you mark your test methods async or async throws to test asynchronously.

What is XCTest Swift?

Use the XCTest framework to write unit tests for your Xcode projects that integrate seamlessly with Xcode's testing workflow. Tests assert that certain conditions are satisfied during code execution, and record test failures (with optional messages) if those conditions aren't satisfied.


2 Answers

I do the following and it works.

expectation = [self expectationWithDescription:@"Testing Async Method Works!"];

[AsynClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
    [expectation fulfil];
    // whatever
}];

[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
    if (error) {
        XCTFail(@"Expectation Failed with error: %@", error);
    }
    NSLog(@"expectation wait until handler finished ");
}];

// do it again

expectation = [self expectationWithDescription:@"Testing Async Method Works!"];

[CallBackClass method:parameter callbackFunction:^(BOOL callbackStatus, NSMutableArray* array) {
    [expectation fulfil];
    // whatever
}];

[self waitForExpectationsWithTimeout:5 handler:^(NSError *error) {
    if (error) {
        XCTFail(@"Expectation Failed with error: %@", error);
    }
    NSLog(@"expectation wait until handler finished ");
}];
like image 130
iceman Avatar answered Sep 30 '22 17:09

iceman


swift

let expectation1 = //your definition
let expectation2 = //your definition

let result = XCTWaiter().wait(for: [expectation1, expectation2], timeout: 10, enforceOrder: true)

if result == .completed {
    //all expectations completed in order
} 
like image 31
Ted Avatar answered Sep 30 '22 19:09

Ted