Asynchronous Unit Tests for iOS

Handling Asynchronous Unit Tests

I’ve been following through on my goal of writing more unit tests for my iOS projects. Though there is definitely an upfront cost, the pay off is priceless. I’m by no means an expert on the subject, but with each test_ that is written I become that much more proficient.

If you are new to the subject checkout these articles

What I’m not a fan of is the repeated logic to handle asynchronous logic for my unit tests. Asynchronous code is much more common now due to GCD and blocks; unforunately it isn’t clear as to how to handle it via unit tests. My testing framework of choice is SenTest. There are many others, but I like you stock components and you get the setup for free when starting an Xcode project, but SenTest “assumes” that all the tests return synchronously. What this essentially means is that your tests will finish before your background executed code completes. #notgood

In order to synchronize your asynchronous code you need to interact with the currentRunLoop. By taking this approach you’ll essentially “pause” any other code execution until your block has finished and returned to the main thread.

DRY

With this block I can interact with the currentRunLoop and properly execute my asynchrous tests.