How to assert asynchronously in XCTest

Issue #644

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import XCTest

extension XCTestCase {
/// Asynchronously assertion
func XCTAssertWait(
timeout: TimeInterval = 1,
_ expression: @escaping () -> Void,
_: String = "",
file _: StaticString = #file,
line _: UInt = #line
) {
let expectation = self.expectation(description: #function)
DispatchQueue.main.asyncAfter(deadline: .now() + timeout) {
expression()
expectation.fulfill()
}

let waiter = XCTWaiter()
XCTAssertTrue(waiter.wait(for: [expectation], timeout: timeout + 1) == .completed)
}
}

Comments