How to write Unit Test for Alamofire request function?

…衆ロ難τιáo~ 提交于 2019-12-23 15:19:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39894064/how-to-write-unit-test-for-alamofire-request-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!