Skip to content

Instantly share code, notes, and snippets.

@cgoldsby
Last active June 4, 2021 13:58
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cgoldsby/73ce46ba4425fb2a8f27 to your computer and use it in GitHub Desktop.
Save cgoldsby/73ce46ba4425fb2a8f27 to your computer and use it in GitHub Desktop.
XCTestCase extension with boilerplate code for unit testing async functions (waiting for expectations)
//
// AsyncTests.swift
//
import XCTest
// MARK: Async Helper Extension
extension XCTestCase {
/// Helper function for setting up a single expectation; call expectation.fulfill() to complete expectation.
func wait(description: String = __FUNCTION__, timeout: NSTimeInterval = 0.5, testingClosure: (expectation: XCTestExpectation) -> Void) {
let expectation = expectationWithDescription(description)
testingClosure(expectation: expectation)
waitForExpectationsWithTimeout(timeout, handler: nil)
}
}
// MARK: Example & Usage
class AsyncTests: XCTestCase {
func testExample() {
// Wrap the the async call using the helper function.
wait { expectation in
// Call your async function that you want to unit test.
asyncFunction { result in
XCTAssertEqual(result, "Success")
// Complete expectation
expectation.fulfill()
}
}
}
}
/// Async Function to unit test.
private func asyncFunction(completion: String -> Void) {
dispatch_async(dispatch_get_main_queue()) {
completion("Success")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment