Skip to content

Instantly share code, notes, and snippets.

@mdb1
Last active July 6, 2023 22:45
Show Gist options
  • Save mdb1/b09873253b39278cff9875d553e9d354 to your computer and use it in GitHub Desktop.
Save mdb1/b09873253b39278cff9875d553e9d354 to your computer and use it in GitHub Desktop.
asyncAssert
import XCTest
public extension XCTestCase {
/// Runs the assertions provided in the main thread in an async way.
/// Useful for testing objects that make async requests (using mocked protocols for the responses)
/// - Parameters:
/// - expectation: The string representation of what we expect.
/// - asyncWaitDuration: Duration in seconds to wait before trying to assert the assertions. Default: 0.05.
/// - assertions: escaping method containing all the assertions.
func asyncAssert(
_ expectation: String,
after asyncWaitDuration: Double = 0.05,
assertions: @escaping () -> Void
) {
let expectation = XCTestExpectation(description: expectation)
DispatchQueue.main.asyncAfter(deadline: .now() + asyncWaitDuration) {
assertions()
expectation.fulfill()
}
wait(for: [expectation], timeout: asyncWaitDuration + 0.01) // 0.01 Delay just in case
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment