Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

There are a few ways to make XCTest wait for async calls in setUp, depending on the specific scenario. Here are three possible methods:

  1. Use XCTestExpectation:

Create a XCTestExpectation object in setUp and fulfill it in the completion block of the async call. Wait for the expectation to be fulfilled before running tests using the wait(for:timeout:) method.

Example code:

func testExample() {
    // ...
}

override func setUp() {
    super.setUp()

    let expectation = XCTestExpectation(description: "Async call completion")

    asyncCall { 
        expectation.fulfill()
    }

    wait(for: [expectation], timeout: 5.0)
}
  1. Use DispatchGroup:

Create a DispatchGroup in setUp and enter it before the async call. Leave the group in the completion block of the async call. Wait for the group to be empty before running tests using the wait() method.

Example code:

func testExample() {
    // ...
}

override func setUp() {
    super.setUp()

    let dispatchGroup = DispatchGroup()
    dispatchGroup.enter()

    asyncCall { 
        // ...
        dispatchGroup.leave()
    }

    dispatchGroup.wait(timeout: DispatchTime.now() + 5.0)
}
  1. Use completion handler:

Modify the asyncCall method to accept a completion handler as a parameter. Call the completion handler in the completion block of the async call. Wait for the async call to complete before running tests using the setUp completion handler.

Example code:

func testExample() {
    // ...
}

override func setUp() {
    super.setUp()

    let expectation = XCTestExpectation(description: "Async call completion")

    asyncCallWithCompletionHandler { 
        expectation.fulfill()
    }

    wait(for: [expectation], timeout: 5.0)
}

func asyncCallWithCompletionHandler(completion: @escaping () -> Void) {
    // ...
    asyncCall { 
        // ...
        completion()
    }
}