Test Asynchronous Code
Swift makes closures so pleasant to read, you may forget they’re there. We have a good start on testing the data task completion handler. But inside that closure, there’s another closure hiding. It’s DispatchQueue.main.async. The part in braces is a closure, scheduled to run on the main thread.
In real life, Cocoa Touch calls the data task completion handler on a background thread. This lets us parse the response without causing the UI to stutter. We can use different approaches for this. I’ve chosen a simple strategy of keeping the decoding in the background, then saving the results on the main thread because that’s what operates the UI.
But be aware that test code executes on the main thread. And when any code schedules ...
Get iOS Unit Testing by Example now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.