Ask Your Question
3

What is the method to make XCTest wait for async calls in setUp, prior to running tests?

asked 2023-06-03 14:30:24 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-03 14:49:01 +0000

djk gravatar image

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()
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-03 14:30:24 +0000

Seen: 14 times

Last updated: Jun 03 '23