Testing asynchronous code in Swift with XCTest expectations

Testing asynchronous callbacks in your Swift code? Try this:

let expectation = expectationWithDescription("Get some sandwiches!")

let client = SandwichClient()

client.getSandwiches { result in 
    switch result {
    case .Success:
        expectation.fulfill() // ?
    case .Failure:
        XCTFail("Expected getSandwiches to succeed, but it failed. ?")
    }
}

waitForExpectationsWithTimeout(10, handler: nil)

Consider using OHHTTPStubs or just stubbing manually to make this run faster.

(Note that result is a simple Result enum like Rob Napier describes in Functional Wish Fulfillment.)

How should you start unit testing your app?

Unit testing for iOS can be lonely — most iOS developers don't seem to be doing it. Should you be writing unit tests? What are the benefits of unit testing, anyway? And if it is worth the effort, how do you get started? Enter your name and email in the boxes to get answers to your questions.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit