Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write Unit Test for Alamofire request function?

I have a project where I'm sending .GET requests to get data from the server and for this I'm using Alamofire & SwiftyJSON.

For example:

I have file "Links", "Requests" and my ViewController.

Links.swift

var getAllData: String {
    return "\(host)api/getalldata"
}

Requests.swift

func getAllData(_ completion:@escaping (_ json: JSON?) -> Void) {
    Alamofire.request(Links.sharedInstance.getAllData).validate().responseJSON { (response) in
        do {
            let json = JSON(data: response.data!)
            completion(json)
        }
    }
}

ViewController

Requests.sharedInstance.getAllData { (json) in
    // ...
}

So, how can I write my Unit Test for this case? I'm just now learning unit testing and in all books there are just local cases and no examples with network cases. Can anyone, please, describe me and help how to write Unit Tests for network requests with Alamofire and SwiftyJSON?

like image 590
Doe Avatar asked Oct 06 '16 10:10

Doe


1 Answers

Since Requests.sharedInstance.getAllData call is a network request, you'll need to use expectation method to create a instance of it so that you can wait for the result of Requests.sharedInstance.getAllData and timeout of it I set 10 seconds otherwise the test fails.

And we are expecting the constants error to be nil and result to not be nil otherwise the test fails too.

import XCTest

class Tests: XCTestCase {

  func testGettingJSON() {
    let ex = expectation(description: "Expecting a JSON data not nil")

    Request.sharedInstance.getAllData { (error, result) in

      XCTAssertNil(error)
      XCTAssertNotNil(result)
      ex.fulfill()

    }

    waitForExpectations(timeout: 10) { (error) in
      if let error = error {
        XCTFail("error: \(error)")
      }
    }
  }

}

Probably you'd want to return an error in order to have details of why your request failed thus your unit tests can validate this info too.

func getAllData(_ completion: @escaping (_ error: NSError?, _ json: String?) -> Void) {
like image 159
Wilson Avatar answered Sep 21 '22 04:09

Wilson