OHHTTPStubs

repository·master·Indexed 26 days ago

https://github.com/alisoftware/ohhttpstubs

A library for stubbing network requests in iOS, macOS, and tvOS applications. It allows developers to simulate network conditions and use fake data for unit testing by intercepting requests made via the Cocoa URL Loading System. Supports Swift and Objective-C, with integration available via CocoaPods, Carthage, and Swift Package Manager.

Tokens
2.7K
Snippets
7
Records
15
Agent score
40%

What's inside OHHTTPStubs

  1. AFNetworking Architecture Overview

    master

    AFNetworking is built on top of the Foundation URL Loading System and is organized into several functional areas:

    NSURLSession

    • AFURLSessionManager
    • AFHTTPSessionManager

    Serialization

    Request Serializers (<AFURLRequestSerialization>)

    • AFHTTPRequestSerializer
    • AFJSONRequestSerializer
    • AFPropertyListRequestSerializer

    Response Serializers (<AFURLResponseSerialization>)

    • AFHTTPResponseSerializer
    • AFJSONResponseSerializer
    • AFXMLParserResponseSerializer
    • AFXMLDocumentResponseSerializer (Mac OS X only)
    • AFPropertyListResponseSerializer
    • AFImageResponseSerializer
    • AFCompoundResponseSerializer

    Additional Functionality

    • AFSecurityPolicy
    • AFNetworkReachabilityManager
  2. Manage stubs in Unit Tests

    master

    When using OHHTTPStubs in unit tests, follow these best practices to ensure test isolation and reliability:

    1. Clean up after each test: Call [HTTPStubs removeAllStubs] in your tearDown method to prevent stubs from leaking into subsequent test cases.
    2. Handle Asynchrony: Ensure you wait for the network request to receive its response before performing assertions and finishing the test case.
  3. Install OHHTTPStubs via CocoaPods

    master

    CocoaPods is the recommended installation method. Choose the subspec based on your language:

    • For Objective-C only: pod 'OHHTTPStubs'
    • For Swift: pod 'OHHTTPStubs/Swift' (includes NSURLSession, JSON, and Swiftier API wrappers)
    pod 'OHHTTPStubs/Swift' # includes the Default subspec, with support for NSURLSession & JSON, and the Swiftier API wrappers
  4. App Store submission and production safety

    master

    OHHTTPStubs is safe to use in apps submitted to the App Store as it does not utilize any private APIs.

    However, because stubs are typically intended for development or testing, you should ensure they do not leak into production environments. To prevent your app from hitting stubs instead of the real network in production, use one of the following strategies:

    • Include OHHTTPStubs only in your test targets.
    • Wrap stubbing logic inside #if DEBUG blocks.
    • Use per-Build-Configuration pods in CocoaPods to ensure the library is only linked during development/testing builds.
  5. Install AFNetworking via CocoaPods

    master

    To integrate AFNetworking into your Xcode project using CocoaPods, ensure you have CocoaPods installed (version 0.39.0+ is required for AFNetworking 3.0.0+). Add the following to your Podfile:

    source 'https://github.com/CocoaPods/Specs.git'
    platform :ios, '11.0'
    
    pod 'AFNetworking', '~> 3.0'

    Then, run pod install in your terminal.

  6. Known limitations of OHHTTPStubs

    master

    When using OHHTTPStubs, be aware of the following technical constraints:

    • Background Sessions: OHHTTPStubs cannot work with background sessions created using [NSURLSessionConfiguration backgroundSessionConfiguration]. These sessions are managed by the iOS Operating System and do not allow custom NSURLProtocols.
    • Data Uploads: The library does not simulate data uploads. Data in the HTTPBody or HTTPBodyStream of an NSURLRequest, or data provided to -[NSURLSession uploadTaskWithRequest:fromData:];, will be ignored. Additionally, the -URLSession:task:didSendBodyData:totalBytesSent:totalBytesExpectedToSend: delegate method will never be called when a request is stubbed.
    • Redirects: There is a known issue where redirects with a zero-second delay may nondeterministically result in a null response (suspected to be an Apple bug).
  7. Stub network requests in Swift

    master

    Use the OHHTTPStubsSwift API to intercept network requests and return fake data from local files. You can compose matchers like isHost and isScheme using logical operators (e.g., &&).

    stub(condition: isHost("mywebservice.com")) { _ in
      // Stub it with our "wsresponse.json" stub file (which is in same bundle as self)
      let stubPath = OHPathForFile("wsresponse.json", type(of: self))
      return fixture(filePath: stubPath!, headers: ["Content-Type":"application/json"])
    }
  8. Stub network requests in Objective-C

    master

    Use [HTTPStubs stubRequestsPassingTest:withStubResponse:] to intercept requests. The passingTest block returns YES if the request should be stubbed, and the withStubResponse block returns an HTTPStubsResponse object containing the fake data and status code.

    [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
      return [request.URL.host isEqualToString:@"mywebservice.com"];
    } withStubResponse:^HTTPStubsResponse*(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 [HTTPStubsResponse responseWithFileAtPath:fixture
                statusCode:200 headers:@{@"Content-Type":@"application/json"}];
    }];
  9. Enable or disable OHHTTPStubs

    master

    By default, OHHTTPStubs is automatically loaded for NSURLConnection, [NSURLSession sharedSession], and NSURLSession instances using defaultSessionConfiguration or ephemeralSessionConfiguration.

    You can globally or per-session control this behavior using:

    • [HTTPStubs setEnabled:] (Objective-C)
    • HTTPStubs.setEnabled(_:) (Swift equivalent)