-
-
Save johndpope-karhoo/67140c703ee38149a921672ee9a826f6 to your computer and use it in GitHub Desktop.
XCTestCase extension with boilerplate code for unit testing async functions (waiting for expectations)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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