### Install Pods Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Run this command after updating your Podfile to install AFNetworking and other dependencies. ```bash $ pod install ``` -------------------------------- ### Install Carthage Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Install Carthage using Homebrew. This is a prerequisite for using Carthage to manage AFNetworking dependencies. ```bash $ brew update $ brew install carthage ``` -------------------------------- ### Install AFNetworking with CocoaPods Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Use this command to install CocoaPods if you haven't already. A specific version of CocoaPods is required for AFNetworking 3.0.0+. ```bash $ gem install cocoapods ``` -------------------------------- ### Debug and Logging Callbacks for Stub Lifecycle Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Install global observer blocks using `onStubActivation:`, `onStubMissing:`, or `afterStubFinish:` to monitor stub matching, un-stubbed requests, and stub delivery completion or errors. ```Swift // Log every intercepted request and the stub name that handled it HTTPStubs.onStubActivation { request, stub, _ in print("✅ \(request.url!) stubbed by '\(stub.name ?? "unnamed")'") } // Fail the test if any request escapes without a matching stub HTTPStubs.onStubMissing { request in XCTFail("⚠️ Unstubbed request: \(request.url!)") } // Log completion (or errors) of every stub HTTPStubs.afterStubFinish { request, stub, _, error in if let e = error { print("❌ \(request.url!) finished with error: \(e)") } else { print("✅ \(request.url!) finished successfully") } } ``` -------------------------------- ### Loading Stubs from Mocktail Files in Objective-C Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Load multiple stubs at once from `.tail` files using the Mocktail format. This Objective-C example demonstrates how to load all mocktails from a specified directory within the test bundle. ```objectivec // Objective-C — load all *.tail files from the "Mocks" folder in the test bundle NSError *error; NSArray *stubs = [HTTPStubs stubRequestsUsingMocktailsAtPath:@"Mocks" inBundle:nil error:&error]; if (error) { XCTFail(@"Failed to load mocktails: %@", error); } // stubs is an NSArray of id, one per .tail file loaded ``` -------------------------------- ### Async Test Handling with XCTestExpectation in Swift Source: https://github.com/alisoftware/ohhttpstubs/wiki/OHHTTPStubs-and-asynchronous-tests This Swift example demonstrates how to correctly handle asynchronous tests using XCTestExpectation. It sets up an expectation, fulfills it upon receiving a response, and then waits for the expectation to be met before making assertions. ```swift func testFoo() { let request = NSURLRequest(...) let responseArrived = self.expectationWithDescription("response of async request has arrived") var receivedData: NSData? NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData!, error: NSError!) in receivedData = data responseArrived.fulfill() } self.waitForExpectationsWithTimeout(timeout) { err in // By the time we reach this code, the while loop has exited // so the response has arrived or the test has timed out XCTAssertNotNil(receivedData, "Received data should not be nil") } } ``` -------------------------------- ### Async Test Handling with XCTestExpectation in Objective-C Source: https://github.com/alisoftware/ohhttpstubs/wiki/OHHTTPStubs-and-asynchronous-tests This Objective-C example shows the correct way to handle asynchronous tests using XCTestExpectation. It creates an expectation, fulfills it in the completion handler, and waits for it with a timeout before asserting. ```objc - (void)testFoo { NSURLRequest* request = ... XCTestExpectation* responseArrived = [self expectationWithDescription:@"response of async request has arrived"]; __block NSData* receivedData = nil; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) { receivedData = data; [responseArrived fulfill]; } ]; [self waitForExpectationsWithTimeout:timeout handler:^{ // By the time we reach this code, the while loop has exited // so the response has arrived or the test has timed out XCTAssertNotNil(receivedData, @"Received data should not be nil"); }]; } ``` -------------------------------- ### HTTPStubs.onStubActivation: / onStubMissing: / afterStubFinish: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Install global observer blocks for stub lifecycle events. These callbacks are useful for debugging and diagnosing stub behavior, including which stubs are activated, which requests are un-stubbed, and the completion status of stubbed responses. ```APIDOC ## `HTTPStubs.onStubActivation:` / `onStubMissing:` / `afterStubFinish:` — Debug and logging callbacks Installs global observer blocks for stub lifecycle events. `onStubActivation:` fires each time a stub matches a request, `onStubMissing:` fires when no stub matches, and `afterStubFinish:` fires when a stub finishes delivering its response (including errors). These are invaluable for diagnosing which stubs are firing, or detecting un-stubbed requests during test runs. ```swift // Log every intercepted request and the stub name that handled it HTTPStubs.onStubActivation { request, stub, _ in print("✅ \(request.url!) stubbed by '\(stub.name ?? \"unnamed\")'") } // Fail the test if any request escapes without a matching stub HTTPStubs.onStubMissing { request in XCTFail("⚠️ Unstubbed request: \(request.url!)") } // Log completion (or errors) of every stub HTTPStubs.afterStubFinish { request, stub, _, error in if let e = error { print("❌ \(request.url!) finished with error: \(e)") } else { print("✅ \(request.url!) finished successfully") } } ``` ``` -------------------------------- ### Stub GET requests with Authorization header (Swift) Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Stub GET requests to a specific host and path that include an Authorization header. This example uses fixture data for the response. ```swift // Stub GET requests to api.example.com/users that include an Authorization header stub(condition: isMethodGET() && isHost("api.example.com") && isPath("/users") && hasHeaderNamed("Authorization")) { _ in let stubPath = OHPathForFile("users_response.json", type(of: self))! return fixture(filePath: stubPath, status: 200, headers: ["Content-Type": "application/json"]) } ``` -------------------------------- ### Shared Network Reachability Monitoring Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Sets up a block to log network reachability status changes and starts monitoring. Use reachability to determine when to retry requests, not to decide whether to send them initially. ```objective-c [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); }]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; ``` -------------------------------- ### Access App's OHHTTPStubs Instance from Test Bundle Source: https://github.com/alisoftware/ohhttpstubs/wiki/A-tricky-case-with-Application-Tests Use this Objective-C code to get a reference to the OHHTTPStubs class instance loaded by the main application bundle. This allows you to interact with stubs set up by the app, separate from those in your test bundle. ```objective-c Class AppOHHTTPStubs = [[NSBundle mainBundle] classNamed:@"OHHTTPStubs"]; ``` -------------------------------- ### Query String Parameter Encoding Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Encodes parameters as a query string for a GET request. ```objective-c [[AFHTTPRequestSerializer serializer] requestWithMethod:@"GET" URLString:URLString parameters:parameters error:nil]; ``` -------------------------------- ### Matching POST Request Body in Objective-C Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Stub POST requests by matching against the request body content. This Objective-C example uses `OHHTTPStubs_HTTPBody` to access the raw body data and compare it with expected credentials. ```objectivec // Objective-C — stub only POST /login with matching credentials #import [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { NSData *body = request.OHHTTPStubs_HTTPBody; NSString *bodyString = [[NSString alloc] initWithData:body encoding:NSUTF8StringEncoding]; return [request.HTTPMethod isEqualToString:@"POST"] && [request.URL.path isEqualToString:@"/login"] && [bodyString isEqualToString:@"user=alice&password=secret"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { return [HTTPStubsResponse responseWithJSONObject:@{@"token": @"xyz"} statusCode:200 headers:nil]; }].name = @"POST /login"; ``` -------------------------------- ### Matching JSON Request Body in Swift Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Stub requests by matching against a JSON payload in the request body using the `hasJsonBody` matcher. This Swift example specifically targets POST requests to `/api/login` with a given username and password. ```swift // Swift — using hasJsonBody matcher stub(condition: isMethodPOST() && isPath("/api/login") && hasJsonBody(["username": "alice", "password": "secret"])) { _ in return HTTPStubsResponse( JSONObject: ["token": "xyz789", "expiresIn": 3600], statusCode: 200, headers: nil ) } ``` -------------------------------- ### Remove All Stubs (Objective-C) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Removes all installed stubs. Essential for unit tests to prevent stub interference between test cases. ```Objective-C // Objective-C - (void)tearDown { [OHHTTPStubs removeAllStubs]; [super tearDown]; } ``` -------------------------------- ### Remove All Stubs (Swift) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Removes all installed stubs. Essential for unit tests to prevent stub interference between test cases. ```Swift // Swift func tearDown() { OHHTTPStubs.removeAllStubs() super.tearDown() } ``` -------------------------------- ### Carthage Swift Version Configuration Source: https://github.com/alisoftware/ohhttpstubs/blob/master/README.md To build the Carthage framework with a specific Swift version, you can use an environment variable or a configuration file. ```bash XCODE_XCCONFIG_FILE= carthage build ``` -------------------------------- ### Carthage Integration Note Source: https://github.com/alisoftware/ohhttpstubs/blob/master/README.md When using Carthage, the built framework includes all features and subspecs of OHHTTPStubs. ```text The `OHHTTPStubs.framework` built with Carthage will include **all** features of `OHHTTPStubs` turned on (in other words, all subspecs of the pod), including `NSURLSession` and `JSON` support, `OHPathHelpers`, `HTTPMessage` and `Mocktail` support, and the Swiftier API. ``` -------------------------------- ### Add OHHTTPStubs/Swift to Podfile Source: https://github.com/alisoftware/ohhttpstubs/blob/master/README.md Use this line in your Podfile if you intend to use OHHTTPStubs from Swift. It includes default subspecs with support for NSURLSession & JSON, and Swift API wrappers. ```ruby pod 'OHHTTPStubs/Swift' # includes the Default subspec, with support for NSURLSession & JSON, and the Swiftier API wrappers ``` -------------------------------- ### Build Response from File Path Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Streams the contents of a file on disk as the response body. Ideal for unit tests with fixture files. Use `OHPathForFile(_:_:)` to resolve filenames. ```Objective-C // Objective-C — fixture file "user_profile.json" is in the test target's bundle [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.path isEqualToString:@"/api/user/42"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSString *path = OHPathForFile(@"user_profile.json", self.class); return [HTTPStubsResponse responseWithFileAtPath:path statusCode:200 headers:@{@"Content-Type": @"application/json"}]; }]; ``` ```Swift stub(condition: isPath("/api/user/42")) { _ in let stubPath = OHPathForFile("user_profile.json", type(of: self))! return fixture(filePath: stubPath, status: 200, headers: ["Content-Type": "application/json"]) } ``` -------------------------------- ### Creating a Data Task Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md This snippet shows how to create and resume a data task for fetching data from a URL. ```APIDOC ## Creating a Data Task This operation fetches data from a specified URL. ### Method GET (Implicit) ### Endpoint http://example.com/upload ### Parameters #### Request Body None ### Request Example ```objective-c NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@", response, responseObject); } }]; [dataTask resume]; ``` ### Response #### Success Response (200) - `response` (NSURLResponse) - The server's response. - `responseObject` (id) - The parsed response object. #### Error Response - `error` (NSError) - An error object if the data task fails. ``` -------------------------------- ### Simulate Slow Network with Request and Response Time Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Use `requestTime:` and `responseTime:` to simulate network latency. `requestTime` delays the response headers, and `responseTime` spreads the data transfer over time. ```Objective-C // Objective-C [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]; }]; ``` ```Swift // Swift stub(isHost("mywebservice.com")) { _ in return OHHTTPStubsResponse(JSONObject:someDict, statusCode:200, headers:nil) .requestTime(1.0, responseTime: 3.0) } ``` -------------------------------- ### `HTTPStubs.stubRequestsPassingTest:withStubResponse:` Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt This is the primary entry point for adding a stub in Objective-C. It accepts a test block to determine if a request should be intercepted and a response block to construct the fake response. Stubs are processed in reverse insertion order. ```APIDOC ## `HTTPStubs.stubRequestsPassingTest:withStubResponse:` — Register a stub for matching requests ### Description The primary entry point for adding a stub. Accepts a test block returning `BOOL` to decide whether a request should be intercepted, and a response block returning the `HTTPStubsResponse` to deliver. Stubs are tested in **reverse insertion order** (last added = highest priority). Returns an `id` that can be used to remove the stub later; OHHTTPStubs holds a strong reference to it internally, so keep it in a `weak` variable in your own code. ### Objective-C Example ```objc // Objective-C — stub only POST requests to /api/login __weak id loginStub = [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.HTTPMethod isEqualToString:@"POST"] && [request.URL.path isEqualToString:@"/api/login"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSDictionary *json = @{ @"token": @"abc123", @"userId": @42 }; return [HTTPStubsResponse responseWithJSONObject:json statusCode:200 headers:nil]; }]; loginStub.name = @"POST /api/login"; // Later, remove just this stub: [HTTPStubs removeStub:loginStub]; ``` ### Swift Example ```swift // Swift — using the OHHTTPStubsSwift helpers weak var loginStub = stub(condition: isMethodPOST() && isPath("/api/login")) { _ in let json: [String: Any] = ["token": "abc123", "userId": 42] return HTTPStubsResponse(JSONObject: json, statusCode: 200, headers: nil) } loginStub?.name = "POST /api/login" // Remove when done: HTTPStubs.removeStub(loginStub!) ``` ``` -------------------------------- ### Simulate Slow/Degraded Networks with responseTime: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Use `responseTime:` to simulate network latency. Positive values are total seconds to stream the response body. Negative values specify download speed in KB/s, using predefined constants like `OHHTTPStubsDownloadSpeedEDGE`. ```Objective-C // Objective-C — 1 second to receive headers, then simulate EDGE download speed [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"api.example.com"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSString *path = OHPathForFile(@"large_response.json", self.class); return [[HTTPStubsResponse responseWithFileAtPath:path statusCode:200 headers:@{@"Content-Type": @"application/json"}] requestTime:1.0 responseTime:OHHTTPStubsDownloadSpeedEDGE]; }]; ``` ```Swift // Swift — 0.5s request delay, then 3G speed stub(condition: isHost("api.example.com")) { _ in let path = OHPathForFile("large_response.json", type(of: self))! return fixture(filePath: path, headers: ["Content-Type": "application/json"]) .requestTime(0.5, responseTime: OHHTTPStubsDownloadSpeed3G) } ``` -------------------------------- ### Simulate Multiple Failures Before Success (Swift) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Return an error response for the first few calls, then a success response. Useful for simulating flaky network conditions or specific API behaviors. ```Swift // Swift var callCounter = 0 stub(…) { callCounter += 1 if callCounter <= 2 { let notConnectedError = NSError(domain:NSURLErrorDomain, code:Int(CFNetworkErrors.CFURLErrorNotConnectedToInternet.rawValue), userInfo:nil) return OHHTTPStubsResponse(error:notConnectedError) } else { let stubData = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding) return OHHTTPStubsResponse(data: stubData!, statusCode:200, headers:nil) } } ``` -------------------------------- ### Creating an Upload Task for a Multi-Part Request, with Progress Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md This snippet demonstrates how to create and resume an upload task for a multi-part request, including progress tracking and completion handling. ```APIDOC ## Creating an Upload Task for a Multi-Part Request, with Progress This operation allows for uploading files as part of a multipart request, with the ability to monitor upload progress. ### Method POST ### Endpoint http://example.com/upload ### Parameters #### Request Body - `formData` (id) - Block to append parts to the multipart form data. - `appendPartWithFileURL:name:fileName:mimeType:error:` - Appends a file part to the form data. ### Request Example ```objective-c NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; } error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSURLSessionUploadTask *uploadTask; uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) { // This is not called back on the main queue. // You are responsible for dispatching to the main queue for UI updates dispatch_async(dispatch_get_main_queue(), ^{ //Update the progress view [progressView setProgress:uploadProgress.fractionCompleted]; }); } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@", response, responseObject); } }]; [uploadTask resume]; ``` ### Response #### Success Response (200) - `response` (NSURLResponse) - The server's response. - `responseObject` (id) - The parsed response object. #### Error Response - `error` (NSError) - An error object if the upload fails. ``` -------------------------------- ### Build Response from Raw Data Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Use this method when the response body is already available in memory as bytes. It's the lowest-level response factory. ```Objective-C // Objective-C [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"api.example.com"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSData *body = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding]; return [HTTPStubsResponse responseWithData:body statusCode:200 headers:@{@"Content-Type": @"text/plain"}]; }]; ``` ```Swift stub(condition: isHost("api.example.com")) { _ in let body = "Hello World!".data(using: .utf8)! return HTTPStubsResponse(data: body, statusCode: 200, headers: ["Content-Type": "text/plain"]) } ``` -------------------------------- ### Create Upload Task with Progress Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Creates a multi-part upload task for a file, including progress tracking and completion handling. Ensure to dispatch UI updates to the main queue. ```objective-c NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id formData) { [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil]; } error:nil]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; NSURLSessionUploadTask *uploadTask; uploadTask = [manager uploadTaskWithStreamedRequest:request progress:^(NSProgress * _Nonnull uploadProgress) { // This is not called back on the main queue. // You are responsible for dispatching to the main queue for UI updates dispatch_async(dispatch_get_main_queue(), ^{ //Update the progress view [progressView setProgress:uploadProgress.fractionCompleted]; }); } completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@", response, responseObject); } }]; [uploadTask resume]; ``` -------------------------------- ### Add AFNetworking to Cartfile Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Specify AFNetworking in your Cartfile to integrate it into your Xcode project using Carthage. Carthage will then build the framework. ```ogdl github "AFNetworking/AFNetworking" ~> 3.0 ``` -------------------------------- ### `stub(condition:response:)` Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt A Swift-idiomatic convenience wrapper for registering stubs, simplifying the process with closures. It allows for composing conditions using logical operators (`&&`, `||`, `!`) for complex matching. ```APIDOC ## `stub(condition:response:)` — Swift convenience wrapper for registering stubs ### Description The Swift-idiomatic shorthand for `stubRequestsPassingTest:withStubResponse:`. Accepts a condition closure (`HTTPStubsTestBlock`) and a response closure, returning an `HTTPStubsDescriptor`. Condition closures from the built-in matchers (`isHost`, `isPath`, `isScheme`, etc.) can be composed with `&&`, `||`, and `!` operators, making complex conditions concise and readable. ### Swift Example 1: Stubbing specific requests ```swift // Stub GET requests to api.example.com/users that include an Authorization header stub(condition: isMethodGET() && isHost("api.example.com") && isPath("/users") && hasHeaderNamed("Authorization")) { _ in let stubPath = OHPathForFile("users_response.json", type(of: self))! return fixture(filePath: stubPath, status: 200, headers: ["Content-Type": "application/json"]) } ``` ### Swift Example 2: Fallback stub ```swift // Stub any request NOT matching the above (fallback / catch-all) stub(condition: !isHost("api.example.com")) { request in let error = NSError(domain: NSURLErrorDomain, code: URLError.notConnectedToInternet.rawValue, userInfo: nil) return HTTPStubsResponse(error: error) } ``` ``` -------------------------------- ### Log Stub Activation Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Set up a block that executes each time a request is stubbed to log the activated stub. This helps in tracking which stub is being used for a given request. ```Objective-C // Objective-C [OHHTTPStubs onStubActivation:^(NSURLRequest *request, id stub) { NSLog(@"%@ stubbed by %@.", request.URL, stub.name); }]; ``` ```Swift // Swift OHHTTPStubs.onStubActivation() { request, stub in println("\(request.URL!) stubbed by \(stub.name).") } ``` -------------------------------- ### Loading Stubs from Raw HTTP Message Files in Objective-C Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Create `HTTPStubsResponse` objects from raw HTTP message files (headers + body) using `responseNamed:inBundle:`. This is useful for replaying exact server responses recorded using tools like `curl`. ```objectivec // Objective-C — "users_list.response" was created with: curl -is https://api.example.com/users > users_list.response [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.path isEqualToString:@"/users"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { // File is in the test bundle; returns status code and headers from the raw HTTP message return [HTTPStubsResponse responseNamed:@"users_list" inBundle:nil]; }]; ``` -------------------------------- ### Simulate Download Speed with Negative Response Time Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Specify a negative value for `responseTime` to simulate download speed in KBytes/s. The response time is computed based on data length and the specified speed. ```Objective-C // Objective-C return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:400 headers:nil] responseTime:OHHTTPStubsDownloadSpeed3G]; ``` ```Swift // Swift return OHHTTPStubsResponse(data:NSData(), statusCode: 400, headers: nil) .responseTime(OHHTTPStubsDownloadSpeed3G) ``` -------------------------------- ### Simulate Multiple Failures Before Success Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Return an error response for the first few calls, then a success response. Useful for simulating flaky network conditions or specific API behaviors. ```Objective-C // Objective-C __block NSUInteger callCount = 0; [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { ... } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { if (++callCount <= 2) { // Return an error the first two times NSError* notConnectedError = [NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil]; return [OHHTTPStubsResponse responseWithError:notConnectedError]; } else { // Return actual data afterwards NSData* stubData = [@ ``` -------------------------------- ### Create Data Task Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Creates a data task to fetch data from a URL. Handles the response and any errors that occur during the request. ```objective-c NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration]; AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration]; NSURL *URL = [NSURL URLWithString:@"http://example.com/upload"]; NSURLRequest *request = [NSURLRequest requestWithURL:URL]; NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { if (error) { NSLog(@"Error: %@", error); } else { NSLog(@"%@ %@", response, responseObject); } }]; [dataTask resume]; ``` -------------------------------- ### responseWithData:statusCode:headers: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Constructs an `HTTPStubsResponse` from raw `NSData`, an HTTP status code, and a header dictionary. This is the most basic method for creating responses when the body is already in memory. ```APIDOC ## `HTTPStubsResponse.responseWithData:statusCode:headers:` — Build a response from raw data Constructs an `HTTPStubsResponse` from an `NSData` body, HTTP status code, and header dictionary. This is the lowest-level response factory method and is the basis for all other convenience constructors. Use this when the response body is already available in memory as bytes. ```objc // Objective-C [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"api.example.com"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSData *body = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding]; return [HTTPStubsResponse responseWithData:body statusCode:200 headers:@{@"Content-Type": @"text/plain"}]; }]; ``` ```swift stub(condition: isHost("api.example.com")) { _ in let body = "Hello World!".data(using: .utf8)! return HTTPStubsResponse(data: body, statusCode: 200, headers: ["Content-Type": "text/plain"]) } ``` ``` -------------------------------- ### Concise Stub Naming Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Apply the `.name = ...` affectation directly for a more concise syntax when the returned descriptor is not needed elsewhere. ```Objective-C // Objective-C [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { ... } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { ... }].name = @"Stub for text files"; ``` ```Swift // Swift stub(…) { _ in … }.name = "Stub for text files" ``` -------------------------------- ### Resolving Fixture File Paths Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Use OHPathForFile and its variants to resolve fixture filenames to absolute paths within test bundles, avoiding hard-coded paths and incorrect bundle references. ```swift // Resolve a file in the same bundle as the calling class (most common case) let jsonPath = OHPathForFile("response.json", type(of: self))! // Resolve a file inside a named sub-bundle (e.g., "Fixtures.bundle") let fixturesBundle = OHResourceBundle("Fixtures", type(of: self))! let jsonPath2 = OHPathForFileInBundle("response.json", fixturesBundle)! // Resolve a file in the app sandbox Documents directory let docPath = OHPathForFileInDocumentsDir("cached_response.json")! stub(condition: isHost("api.example.com")) { _ in return fixture(filePath: jsonPath, status: 200, headers: ["Content-Type": "application/json"]) } ``` -------------------------------- ### Stub Requests with File Content (Swift) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Use this to stub requests with the content of a file from your application bundle. Ensure the file is correctly linked to your Unit Test target. Uses OHPathForFile helper. Note: Swift 2 syntax uses `self.dynamicType`. ```Swift // Swift stub(isHost("mywebservice.com")) { request in // Stub it with our "wsresponse.json" stub file return OHHTTPStubsResponse( fileAtPath: OHPathForFile("wsresponse.json", type(of: self))!, statusCode: 200, headers: ["Content-Type":"application/json"] ) } ``` -------------------------------- ### Stub Requests with File Content (Objective-C) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Use this to stub requests with the content of a file from your application bundle. Ensure the file is correctly linked to your Unit Test target. Uses OHPathForFile helper. ```Objective-C // Objective-C [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"mywebservice.com"]; } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { // Stub it with our "wsresponse.json" stub file return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFile(@"wsresponse.json",self.class) statusCode:200 headers:@{@"Content-Type":@"application/json"}]; }]; ``` -------------------------------- ### Fixing project.pbxproj for Manual Integration Source: https://github.com/alisoftware/ohhttpstubs/wiki/Detailed-Library-Integration-instructions Manually edit the project.pbxproj file to correct the path for libOHHTTPStubs.a when using manual integration to resolve Xcode build issues. ```bash path = "libOHHTTPStubs.a"; ``` -------------------------------- ### Add -ObjC Flag for Category Methods Source: https://github.com/alisoftware/ohhttpstubs/wiki/Detailed-Library-Integration-instructions Ensure the '-ObjC' flag is present in your target's 'Other Linker Flags' build setting to resolve 'unrecognized selector' errors when using OHHTTPStubs category methods. ```bash -ObjC ``` -------------------------------- ### CocoaPods Configuration for Debug Builds Source: https://github.com/alisoftware/ohhttpstubs/wiki/Detailed-Library-Integration-instructions Configure your Podfile to include OHHTTPStubs only for Debug configurations, preventing it from being included in release builds for the App Store. ```ruby pod 'OHHTTPStubs', :configuration => ['Debug'] ``` -------------------------------- ### Import OHHTTPStubs Header Source: https://github.com/alisoftware/ohhttpstubs/wiki/Detailed-Library-Integration-instructions Use this import statement when you need to access OHHTTPStubs classes in your Objective-C code. ```objective-c #import ``` -------------------------------- ### responseWithFileAtPath:statusCode:headers: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Streams the contents of a file on disk as the response body. This is ideal for unit tests that use fixture files for response data. ```APIDOC ## `HTTPStubsResponse.responseWithFileAtPath:statusCode:headers:` — Build a response from a fixture file Streams the contents of a file on disk as the response body. Ideal for unit tests where fixture JSON (or other data) files are added to the test bundle. Use `OHPathForFile(_:_:)` to resolve a filename to its full bundle path without hardcoding paths. ```objc // Objective-C — fixture file "user_profile.json" is in the test target's bundle [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.path isEqualToString:@"/api/user/42"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSString *path = OHPathForFile(@"user_profile.json", self.class); return [HTTPStubsResponse responseWithFileAtPath:path statusCode:200 headers:@{@"Content-Type": @"application/json"}]; }]; ``` ```swift stub(condition: isPath("/api/user/42")) { _ in let stubPath = OHPathForFile("user_profile.json", type(of: self))! return fixture(filePath: stubPath, status: 200, headers: ["Content-Type": "application/json"]) } ``` ``` -------------------------------- ### CocoaPods Subspec Table Source: https://github.com/alisoftware/ohhttpstubs/blob/master/README.md This table details the available subspecs for OHHTTPStubs and their dependencies, allowing for granular inclusion of features. ```markdown | Subspec | Core | NSURLSession | JSON | Swift | OHPathHelpers | HTTPMessage | Mocktail | | --------------------------------- | :--: | :----------: | :--: | :---: | :-----------: | :---------: | :------: | | `pod 'OHHTTPStubs'` | ✅ | ✅ | ✅ | | ✅ | | | | `pod 'OHHTTPStubs/Default'` | ✅ | ✅ | ✅ | | ✅ | | | | `pod 'OHHTTPStubs/Swift'` | ✅ | ✅ | ✅ | ✅ | ✅ | | | | `pod 'OHHTTPStubs/Core'` | ✅ | | | | | | | | `pod 'OHHTTPStubs/NSURLSession'` | ✅ | ✅ | | | | | | | `pod 'OHHTTPStubs/JSON'` | ✅ | | ✅ | | | | | | `pod 'OHHTTPStubs/OHPathHelpers'` | | | | | ✅ | | | | `pod 'OHHTTPStubs/HTTPMessage'` | ✅ | | | | | ✅ | | | `pod 'OHHTTPStubs/Mocktail'` | ✅ | | | | | | ✅ | ``` -------------------------------- ### Fallback stub for non-matching requests (Swift) Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt This Swift snippet acts as a fallback or catch-all stub for any requests not matching previous conditions, returning a network error. ```swift // Stub any request NOT matching the above (fallback / catch-all) stub(condition: !isHost("api.example.com")) { request in let error = NSError(domain: NSURLErrorDomain, code: URLError.notConnectedToInternet.rawValue, userInfo: nil) return HTTPStubsResponse(error: error) } ``` -------------------------------- ### responseWithJSONObject:statusCode:headers: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt A convenience constructor that serializes a JSON object (`NSDictionary` or `NSArray`) and automatically sets the `Content-Type` to `application/json` if not provided. Useful for APIs that return JSON. ```APIDOC ## `HTTPStubsResponse.responseWithJSONObject:statusCode:headers:` — Build a response from a JSON object Convenience constructor (from the `OHHTTPStubs/JSON` subspec) that serializes an `NSDictionary` or `NSArray` using `NSJSONSerialization` and automatically appends `Content-Type: application/json` if not provided. Eliminates boilerplate serialization in tests that deal with JSON APIs. ```objc // Objective-C [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"api.example.com"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSDictionary *payload = @{ @"items": @[@{@"id": @1, @"name": @"Widget"}, @{@"id": @2, @"name": @"Gadget"}], @"total": @2 }; return [HTTPStubsResponse responseWithJSONObject:payload statusCode:200 headers:nil]; }]; ``` ```swift stub(condition: isHost("api.example.com")) { _ in let payload: [String: Any] = [ "items": [["id": 1, "name": "Widget"], ["id": 2, "name": "Gadget"]], "total": 2 ] return HTTPStubsResponse(JSONObject: payload, statusCode: 200, headers: nil) } ``` ``` -------------------------------- ### Stub Requests with NSData (Swift) Source: https://github.com/alisoftware/ohhttpstubs/wiki/Usage-Examples Stubs network requests to a specific host using Swift helper methods and returns a response with the given NSData. This approach leverages trailing closures for conciseness. ```swift // Swift stub(isHost("mywebservice.com")) { _ in let stubData = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding) return OHHTTPStubsResponse(data: stubData!, statusCode:200, headers:nil) }) ``` -------------------------------- ### Stub POST Request by Body Parameters Source: https://github.com/alisoftware/ohhttpstubs/wiki/Testing-for-the-request-body-in-your-stubs Stub a POST request to \"/login\" only if the \"user\" is \"foo\" and the \"password\" is \"bar\". This is useful for simulating specific API interactions. ```objc [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { NSDictionary* requestParams = [NSURLProtocol propertyForKey:NSURLRequestParametersMetadataKey inRequest:request]; // Here you can also retrieve any other meta-data that you'd have added in your implementation in step 1 // (in case you decided to write some code to add other custom meta-data automatically to all AFN requests) // Only stub POST requests to "/login" with "user" = "foo" & "password" = "bar" return [request.HTTPMethod isEqualToString:@"POST"] && [request.URL.path isEqualToString:@"/login"] && [requestParams[@"user"] isEqualToString:@"foo"] && [requestParams[@"password"] isEqualToString:@"bar"]; } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) { return [OHHTTPStubsResponse responseWithData:validLoginResponseData statusCode:200 headers:headers]; }].name = @"login"; ``` -------------------------------- ### Add AFNetworking to Podfile Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Specify AFNetworking in your Podfile to integrate it into your Xcode project using CocoaPods. Ensure the platform version is compatible. ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '11.0' pod 'AFNetworking', '~> 3.0' ``` -------------------------------- ### responseTime: / requestTime:responseTime: Source: https://context7.com/alisoftware/ohhttpstubs/llms.txt Simulate slow or degraded networks by introducing artificial latency to responses. `responseTime` can be a positive value in seconds for total streaming time, or a negative value representing download speed in KB/s. ```APIDOC ## `responseTime:` / `requestTime:responseTime:` — Simulate slow or degraded networks Chainable setters on `HTTPStubsResponse` that introduce artificial latency. A positive `responseTime` value is interpreted as total seconds to stream the response body. A **negative** value is interpreted as a **download speed in KB/s**, enabling use of the built-in `OHHTTPStubsDownloadSpeedGPRS`, `OHHTTPStubsDownloadSpeedEDGE`, `OHHTTPStubsDownloadSpeed3G`, `OHHTTPStubsDownloadSpeed3GPlus`, and `OHHTTPStubsDownloadSpeedWifi` constants. ```objc // Objective-C — 1 second to receive headers, then simulate EDGE download speed [HTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { return [request.URL.host isEqualToString:@"api.example.com"]; } withStubResponse:^HTTPStubsResponse *(NSURLRequest *request) { NSString *path = OHPathForFile(@"large_response.json", self.class); return [[HTTPStubsResponse responseWithFileAtPath:path statusCode:200 headers:@{@"Content-Type": @"application/json"}] requestTime:1.0 responseTime:OHHTTPStubsDownloadSpeedEDGE]; }]; ``` ```swift // Swift — 0.5s request delay, then 3G speed stub(condition: isHost("api.example.com")) { _ in let path = OHPathForFile("large_response.json", type(of: self))! return fixture(filePath: path, headers: ["Content-Type": "application/json"]) .requestTime(0.5, responseTime: OHHTTPStubsDownloadSpeed3G) } ``` ``` -------------------------------- ### Network Reachability Manager Source: https://github.com/alisoftware/ohhttpstubs/blob/master/Pods/AFNetworking/README.md Information on using AFNetworkReachabilityManager to monitor network connectivity. ```APIDOC ## Network Reachability Manager `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. ### Shared Network Reachability This section describes how to get the shared network reachability manager and set up a block to be called when the network status changes. #### Method Start Monitoring #### Parameters - `setReachabilityStatusChangeBlock:` - A block that is called when the network status changes. #### Request Example ```objective-c [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status)); }]; [[AFNetworkReachabilityManager sharedManager] startMonitoring]; ``` ```