Asynchronous Unit Testing in Swift
Fortunately, this is where Xcode 6′s asynchronous testing comes in. It allows us to create
XCTestExpectation
objects, which are not tests but timers. We create expectations withXCTestCase
’sexpectationWithDescription()
, which just takes a string to describe what we’re waiting for. Then, prior to the end of thetest…
method, we callwaitForExpectationsWithTimeout()
, passing in a timeout period and a completion handler closure. This prevents the test method from exiting until either the timeout expires, or some asynchronous test code callsfulfill()
on the expectation object, which unblocks it.
Update (2014-07-22): Mattt Thompson:
Perhaps the most exciting feature added in Xcode 6 is built-in support for asynchronous testing, with the
XCTestExpectation
class. Now, tests can wait for a specified length of time for certain conditions to be satisfied, without resorting to complicated GCD incantations.