如何编写Alamofire请求功能的单元测试? [英] How to write Unit Test for Alamofire request function?
问题描述
我有一个项目,我正在发送.GET请求以从服务器获取数据,为此,我正在使用Alamofire& SwiftyJSON。
I have a project where I'm sending .GET requests to get data from the server and for this I'm using Alamofire & SwiftyJSON.
例如:
我有文件 Links, Requests和ViewController。
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
// ...
}
那么,如何编写单元测试对于这种情况?我现在正在学习单元测试,并且所有书籍中都只有本地案例,而没有网络案例。有谁能描述我,并帮助如何使用Alamofire和SwiftyJSON为网络请求编写单元测试?
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?
推荐答案
自 Requests.sharedInstance.getAllData
调用是一个网络请求,您需要使用期望方法创建一个实例,以便您可以等待 Requests.sharedInstance.getAllData
并设置其超时时间为10秒,否则测试将失败。
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.
我们期望常量错误
为无
,而结果
为不请 nil
否则测试也将失败。
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) {
这篇关于如何编写Alamofire请求功能的单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!