Handling errors

Using try! instead of try in the call to JSONObjectWithData(_:options:), we tell the compiler: "Trust me on this: This method will never fail.". Let's write a test that feeds in wrong data and asserts that an error is thrown:

func testLogin_ThrowsErrorWhenJSONIsInvalid() {
    
    var theError: ErrorType?
    let completion = { (error: ErrorType?) in
        theError = error
    }
    sut.loginUserWithName("dasdom",
        password: "1234",
        completion: completion)
    
    let responseData = NSData()
    mockURLSession.completionHandler?(responseData, nil, nil)
    
    XCTAssertNotNil(theError)
}

In the test, we call the completion handler with an empty data object.

Run the tests. The implementation code crashes because the deserialization fails and throws an error. Let's change the code ...

Get Test-Driven iOS Development with Swift 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.