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 

  waitForExpectations(timeout: 1) { (error) in 

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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.