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

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

功能列表:

  1. 模拟慢网络,检查你的应用在差网络情况下的行为
  2. 写单元测试,模拟返回数据

基本用法

  1. 拦截域名为mywebservice.com的http请求,并返回wsresponse.json文件里面的数据,可以设置网络状态吗,请求头格式,以及请求时间和响应时间

    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
      return [request.URL.host isEqualToString:@"mywebservice.com"];
    } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
      // Stub it with our "wsresponse.json" stub file (which is in same bundle as self)
      NSString* fixture = OHPathForFile(@"wsresponse.json", self.class);
      return [OHHTTPStubsResponse responseWithFileAtPath:fixture
                statusCode:200 headers:@{@"Content-Type":@"application/json"}];
    }];
    

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

  • 可以模拟慢网络情况,给OHHTTPStubsResponse设置requestTime或者responseTime

      [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
          return [request.URL.host isEqualToString:@"mywebservice.com"];
      } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
          return [[OHHTTPStubsResponse responseWithJSONObject:someDict statusCode:200 headers:nil]
                  requestTime:1.0 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
    

    然后根据data数据量来间接的计算下载/加载时间

      return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:400 headers:nil]
              responseTime:OHHTTPStubsDownloadSpeed3G];
    
  • 同样,你也可以模拟网络错误情况

      NSError* notConnectedError = [NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil];
      return [OHHTTPStubsResponse responseWithError:notConnectedError];
    

自动加载

Thanks to method swizzling, OHHTTPStubs is automatically loaded and installed both for:

  • requests made using NSURLConnection or [NSURLSession sharedSession];
  • requests made using a NSURLSession created using a [NSURLSessionConfiguration defaultSessionConfiguration] or [NSURLSessionConfiguration ephemeralSessionConfiguration] configuration (using [NSURLSession sessionWithConfiguration:…]-like methods).

If you need to disable (and re-enable) OHHTTPStubs — globally or
per NSURLSession — you can use [OHHTTPStubs setEnabled:] / [OHHTTPStubs setEnabled:forSessionConfiguration:].

注意事项

  • OHHTTPStubs不可用于后台请求
    (sessions created using [NSURLSessionConfiguration backgroundSessionConfiguration]) 因为后台请求不允许用自定义的 NSURLProtocols 它是由iOS系统自己进行管理的
  • OHHTTPStubs不能模拟数据上传
    The NSURLProtocolClient @protocol does not provide a way to signal the delegate that data has been sent (only that some has been loaded), so any data in the HTTPBody or HTTPBodyStream of an NSURLRequest, or data provided to -[NSURLSession uploadTaskWithRequest:fromData:]; will be ignored, and more importantly, the -URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: delegate method will never be called when you stub the request using OHHTTPStubs.

提交至苹果商店

使用OHHTTPStubs的应用可以提交至苹果商店,因为它不包含私有的API。
但是一般情况下你使用它都是在开发阶段,而且当你提交苹果商店的时候并不需要他模拟网络,所以当你的工程包含OHHTTPStubs类库的时候你要小心,你可以在提交商店的时候移除该类库或者使用#if DEBUG用来区分在正式环境下关闭它。

https://github.com/AliSoftware/OHHTTPStubs

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容