There are a few ways to make XCTest wait for async calls in setUp, depending on the specific scenario. Here are three possible methods:
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)
}
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)
}
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()
}
}
Asked: 2023-06-03 14:30:24 +0000
Seen: 14 times
Last updated: Jun 03 '23