Skip to content

Instantly share code, notes, and snippets.

@ilyapuchka
Created December 30, 2015 12:42
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 ilyapuchka/c682ad4695acb4cfa938 to your computer and use it in GitHub Desktop.
Save ilyapuchka/c682ad4695acb4cfa938 to your computer and use it in GitHub Desktop.
Better XCTest expectations
extension XCTestCase {
func fail(expectation: XCTestExpectation?, file: String = __FILE__, line: UInt = __LINE__) {
expectation?.fulfill()
self.recordFailureWithDescription("Expectation failed: \(expectation)", inFile: file, atLine: line, expected: false)
}
func fulfill(expectation: XCTestExpectation?, @autoclosure condition: ()->Bool = true, file: String = __FILE__, line: UInt = __LINE__) {
guard let expectation = expectation else { return }
if condition() {
expectation.fulfill()
}
else {
fail(expectation, file: file, line: line)
}
}
}
//Usage:
func test() {
//weakify expectation to be sure we never fullfill it after timeout
weak var expectation = expectationWithDescription("some description")
//some async operation with completion block
//weakify self if operation is retianed somehow (maybe not directly) by test case
doAsync { [weak self] in
self?.fulfill(expectation, condition: someCondition)
//any additional asserts
}
waitForExpectationsWithTimeout(5, handler: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment