How to write Unit Test for Alamofire request function?
Asked Answered
C

1

6

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?

Callant answered 6/10, 2016 at 10:52 Comment(1)
Possible duplicate of Unit Testing HTTP traffic in Alamofire appContaminate
F
6

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) {
Frequent answered 6/10, 2016 at 12:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.