Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.