Asynchronous unit tests using XCTestExpectation

I came across an interesting blog post by Phil Beauvoir about Asynchronous Unit Testing in Xcode 6 using the new XCTestExpectation. It explains how he converted existing Objective-C asynchronous iOS unit tests to Swift, at the same time making them more efficient and readable by using an instance of XCTestExpectation and waitForExpectationsWithTimeout().

XCTestExpectation is a dirt simple class with 1 method: fulfill(). Create an instance of it and call fulfill() when the expectation has been met.

In your test assert section, call waitForExpectationsWithTimeout(), passing the XCTestExpectation, and Voila! Asynchronous unit tests.

As opposed to using a spin loop, this explicitly informs the XCTest framework that your test is waiting for an asynchronous event to happen, allowing it to perform other tests while waiting.

One thought on “Asynchronous unit tests using XCTestExpectation

  1. I’ve started using expectations a bit. They are really good in that it’s allowed me to remove some test support classes full of similar functionality for handling async code. Definitely worth the effort to apply.

Leave a Reply