Handling errors

Using try! instead of try in the call to jsonObject(with:options:), you 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 test_Login_WhenJSONIsInvalid_ReturnsError() { 
  
  
  mockURLSession = MockURLSession(data: Data(), 
                                  urlResponse: nil, 
                                  error: nil) 
  sut.session = mockURLSession 
  
 
  let errorExpectation = expectation(description: "Error") 
  var catchedError: Error? = nil 
  sut.loginUser(withName: "Foo", password: "Bar") { (token, error) in 
    catchedError = error 
    errorExpectation.fulfill() 
  } 
   

  waitForExpectations(timeout: 1) { (error) in 
    XCTAssertNotNil(catchedError) 
  } 
} 

In the test, you feed an empty data object to the completion handler.

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