[英]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. 我有一个项目,我发送.GET请求从服务器获取数据,为此我使用Alamofire和SwiftyJSON。
For example: 例如:
I have file "Links", "Requests" and my ViewController. 我有文件“链接”,“请求”和我的ViewController。
Links.swift Links.swift
var getAllData: String {
return "\(host)api/getalldata"
}
Requests.swift 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?
请允许任何人描述我并帮助如何使用Alamofire和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. 由于
Requests.sharedInstance.getAllData
调用是一个网络请求,你需要使用expectation方法创建它的实例,这样你就可以等待Requests.sharedInstance.getAllData
的结果和超时了我设置10秒否则测试失败。
And we are expecting the constants error
to be nil
and result
to not be nil
otherwise the test fails too. 并且我们期望常量
error
nil
并且result
不 nil
否则测试也会失败。
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) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.