Skip to content

Instantly share code, notes, and snippets.

@AvdLee
Last active May 20, 2017 14:21
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 AvdLee/f184df046c99e5e5f3b99b542c419e63 to your computer and use it in GitHub Desktop.
Save AvdLee/f184df046c99e5e5f3b99b542c419e63 to your computer and use it in GitHub Desktop.
Wait for a callback to be a given value in Xcode unit tests. As pure Swift objects can't be used with NSPredicate, this can help to test simple results.
//
// XCTestExtensions.swift
//
// Created by Antoine van der Lee on 20/05/2017.
// Copyright © 2017 AvdLee. All rights reserved.
//
import XCTest
extension XCTestCase {
/// Checks for the callback to be the expected value within the given timeout.
///
/// - Parameters:
/// - callback: The callback which returns the value.
/// - expectedValue: The expected value.
/// - timeout: The timeout in which the value should result in the expectedValue.
func waitFor<T: Equatable>(callback: () -> T, toBe expectedValue: T, withTimeout timeout: TimeInterval) {
let expectation = self.expectation(description: "Wait for callback to be expectedValue")
let end = Date().addingTimeInterval(timeout)
while callback() != expectedValue && 0 < end.timeIntervalSinceNow {
if RunLoop.current.run(mode: RunLoopMode.defaultRunLoopMode, before: Date(timeIntervalSinceNow: 0.002)) {
Thread.sleep(forTimeInterval: 0.002)
}
}
if callback() != expectedValue {
XCTFail("Timed out waiting for callback to be true")
} else {
expectation.fulfill()
}
waitForExpectations(timeout: timeout, handler: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment