swift单元测试(六)三方网络请求框架OHHTTPStubs 的使用

1、OHHTTPStubs 的介绍

        在你的服务器没有准备妥当或者在你需要模拟数据进行本地开发时,OHHTTPStubs是一个很好的可以加速测试和开发的工具。OHHTTPStubs可使用伪造的网络数据和模拟的缓慢网络来测试你的应用程序,从而检测你的应用程序在不佳的网络环境中的行为,并使用伪造的网络数据编写单元测试

    OHHTTPStubsResponse可以指定为文件,图片,data数据,或者json对象。比较灵活

 

2、OHHTTPStubs 的使用

1)cocopod导入框架

pod 'OHHTTPStubs/Swift',:configurations => ['Debug']
#debug的配置意思是只用于debug环境,在代码中也需要进行debug判断

2)在swift或者测试文件中引入

import OHHTTPStubs

3)本文的案例是利用Alamofire网络框架+ SwiftyJSON解析解析数据,编写一个请求及响应的处理

所以需要同时利用pod导入 Alamofire 和 SwiftyJSON

请求的代码如下

func StubDataClick(_ sender: Any) {
        Alamofire.request("http://mywebservice.com", method: .get, parameters: nil, encoding: JSONEncoding.default).responseJSON { (respons) in
            print("response: ", respons.response as Any)
            print("result: ",respons.result)

            switch respons.result{
            case .success(let value):
                let json = JSON(value)
                 self.textView.text = json.rawString()
                print("JSON: ", json)
            case .failure(let error):
                 print("error: ",error)
                 self.textView.text = (error as! NSError).description
            }

        }
}

4)在网络请求执行前,需要配置拦截请求的响应

有如下几种情况的配置:

(1)自定义返回的结果数据

OHHTTPStubs.stubRequests(passingTest: { (request) -> Bool in
            return request.url?.host == "mywebservice.com"
        }) { (request) -> OHHTTPStubsResponse in
            let array = ["hello", "world"]
            return OHHTTPStubsResponse.init(jsonObject: array, statusCode: 200, headers: nil)
        }

打印的返回结果:

(2)返回项目中配置的json格式文件(可以自己任意配以一个json格式的文件)

OHHTTPStubs.stubRequests(passingTest: { (request) -> Bool in
            return request.url?.host == "mywebservice.com"
        }) { (request) -> OHHTTPStubsResponse in
            let stubPath = OHPathForFile("abbaData.json", type(of: self))
            return fixture(filePath: stubPath!, status: 200, headers: ["Content-Type":"application/json"])
        }

打印的结果: 

(3)模拟网络慢的情况

慢网络的情况就是请求响应的时间长,返回数据慢

/*
         responseTime 可以指定具体的数值 例如3.0
         你也可以用枚举值来定义responseTime
         
         OHHTTPStubsDownloadSpeedGPRS   =    -7 =    7 KB/s =    56 kbps
         OHHTTPStubsDownloadSpeedEDGE   =   -16 =   16 KB/s =   128 kbps
         OHHTTPStubsDownloadSpeed3G     =  -400 =  400 KB/s =  3200 kbps
         OHHTTPStubsDownloadSpeed3GPlus =  -900 =  900 KB/s =  7200 kbps
         OHHTTPStubsDownloadSpeedWifi   = -1500 = 1500 KB/s = 12000 kbps
         */
        OHHTTPStubs.stubRequests(passingTest: { (request) -> Bool in
            return request.url?.host == "mywebservice.com"
        }) { (request) -> OHHTTPStubsResponse in
            let stubPath = OHPathForFile("abbaData.json", type(of: self))
            return fixture(filePath: stubPath!, status: 200, headers: ["Content-Type":"application/json"]).requestTime(1.0, responseTime: OHHTTPStubsDownloadSpeedWifi)
        }

打印的返回结果:

(4)模拟网络错误的情况

OHHTTPStubs.stubRequests(passingTest: { (request) -> Bool in
            return request.url?.host == "mywebservice.com"
        }) { (request) -> OHHTTPStubsResponse in
            let error : NSError = NSError.init(domain: NSURLErrorDomain, code: 500, userInfo: ["describe":"netwoek is error"])
            return OHHTTPStubsResponse.init(error: error)
        }

打印返回的错误详情:

3、结论

优点:

1)模拟慢网络,检查你的应用在差网络情况下的行为

2)写单元测试,模拟返回数据

3)使用OHHTTPStubs的应用可以提交至苹果商店,因为它不包含私有的API。

4)OHHTTPStubsResponse可以指定为文件,图片,data数据,或者json对象。比较灵活

缺点:

1)OHHTTPStubs不可用于后台请求数据,因为后台请求不允许用自定义的 NSURLProtocols 它是由iOS系统自己进行管理的

2)OHHTTPStubs不能模拟数据上传

参考链接:

iOS网络请求模拟库OHHTTPStubs的介绍和使用

iOS模拟网络之OHHTTPStubs库的介绍与使用

猜你喜欢

转载自blog.csdn.net/lin1109221208/article/details/93051140