Forked from cgoldsby/XCTestCase+Expectation.swift
Last active
December 1, 2016 10:59
-
-
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)
This file contains 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 = "\(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") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated to Swift 3