简体   繁体   中英

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?

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) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM