如何用Alamofire为http请求编写单元测试?

时间:2017-07-14 00:15:54

标签: ios swift unit-testing alamofire

我的应用正在使用Alamofire发送http请求,并想为此部分编写一些单元测试。我创建了一些json文件作为响应。如何阻止Alamofire请求并让Alamofire返回json文件中的内容作为响应?我们可以使用方法调配来替换函数吗?

2 个答案:

答案 0 :(得分:2)

使用类似OHHTTPStubs的框架来存根网络请求或发出真实的网络请求。在任何一种情况下,XCTest都有各种异步等待方法,例如XCTExpectation

答案 1 :(得分:1)

这是等待一些异步回调的方法。这是最低限度的测试。您可以根据测试要求进行更多改进

func testCheckThatTheNetworkResponseIsEqualToTheExpectedResult() {

    //expected result 
    let expectedResult: [String:Any] = ["data":"somedata","order_number":2]

    let expectations = expectation(description: "The Response result match the expected results")

    if let requestUrl = URL(string: "some url to fetch data from") {

        let request = Alamofire.request(requestUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil)
        request.responseJSON(completionHandler: { (response) in
            switch response.result {
            case .success(let result):
                //do the checking with expected result
                //AssertEqual or whatever you need to do with the data
                //finally fullfill the expectation
                expectations.fulfill()
            case .failure(let error):
                //this is failed case
                XCTFail("Server response failed : \(error.localizedDescription)")
                expectations.fulfill()
            }
        })

        //wait for some time for the expectation (you can wait here more than 30 sec, depending on the time for the response)
        waitForExpectations(timeout: 30, handler: { (error) in
            if let error = error {
                print("Failed : \(error.localizedDescription)")
            }

        })
    }

}