Skip to content

Instantly share code, notes, and snippets.

@avdyushin
Forked from cgoldsby/XCTestCase+Expectation.swift
Last active December 1, 2016 10:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save avdyushin/e3e177482d635682d49e4e80d988e15a to your computer and use it in GitHub Desktop.
Save avdyushin/e3e177482d635682d49e4e80d988e15a 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 = "\(NSURL(fileURLWithPath: #file).lastPathComponent ?? #file) \(#function)", timeout: TimeInterval = 0.5, testingClosure: (_ expectation: XCTestExpectation) -> Void) {
let expectation = expectationWithDescription(description)
testingClosure(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")
}
}
@avdyushin
Copy link
Author

Updated to Swift 3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment