• Stars
    star
    5,039
  • Rank 8,274 (Top 0.2 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 12 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Stub your network requests easily! Test your apps with fake network data and custom response time, response code and headers!

OHHTTPStubs

Platform Language: Swift-2.x/3.x/4.x/5.x Build Status

Version Carthage Supported Swift Package Manager Supported

OHHTTPStubs is a library designed to stub your network requests very easily. It can help you:

  • test your apps with fake network data (stubbed from file) and simulate slow networks, to check your application behavior in bad network conditions
  • write unit tests that use fake network data from your fixtures.

It works with NSURLConnection, NSURLSession, AFNetworking, Alamofire or any networking framework that use Cocoa's URL Loading System.

Donate


Documentation & Usage Examples

OHHTTPStubs headers are fully documented using Appledoc-like / Headerdoc-like comments in the header files. You can also read the online documentation here.

Basic example

In Objective-C
[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"}];
}];
In Swift

This example is using the Swift helpers found in OHHTTPStubsSwift.swift provided by the OHHTTPStubs/Swift subspec or OHHTTPStubs package.

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"])
}

Note: if you're using OHHTTPStubs's Swiftier API (OHHTTPStubsSwift.swift and the Swift subspec or OHTTPStubsSwift package), you can also compose the matcher functions like this: stub(isScheme("http") && isHost("myhost")) { … }

More examples & Help Topics

Recording requests to replay them later

Instead of writing the content of the stubs you want to use manually, you can use tools like SWHttpTrafficRecorder to record network requests into files. This way you can later use those files as stub responses.
This tool can record all three formats that are supported by OHHTTPStubs (the HTTPMessage format, the simple response boby/content file, and the Mocktail format).

(There are also other ways to perform a similar task, including using curl -is <url> >foo.response to generate files compatible with the HTTPMessage format, or using other network recording libraries similar to SWHttpTrafficRecorder).

Compatibility

  • OHHTTPStubs is compatible with iOS5+, OS X 10.7+, tvOS.
  • OHHTTPStubs also works with NSURLSession as well as any network library wrapping them.
  • OHHTTPStubs is fully compatible with Swift 3.x, 4.x and Swift 5.x.

Nullability annotations have also been added to the ObjC API to allow a cleaner API when used from Swift even if you don't use the dedicated Swift API wrapper provided by OHHTTPStubsSwift.swift.

Updating to Version 9.0+
  • All classes dropped the OH prefix (OHHHTTPStubs -> HTTPStubs, OHHTTPStubsResponse -> HTTPStubsResponse, etc).
  • The OHPathHelpers class was renamed HTTPStubsPathHelpers.
  • No method and module names were changed.

Installing in your projects

CocoaPods

Using CocoaPods is the recommended way.

  • If you intend to use OHHTTPStubs from Objective-C only, add pod 'OHHTTPStubs' to your Podfile.
  • If you intend to use OHHTTPStubs from Swift, add pod 'OHHTTPStubs/Swift' to your Podfile instead.
pod 'OHHTTPStubs/Swift' # includes the Default subspec, with support for NSURLSession & JSON, and the Swiftier API wrappers

All available subspecs

OHHTTPStubs is split into subspecs so that when using Cocoapods, you can get only what you need, no more, no less.

  • The default subspec includes NSURLSession, JSON, and OHPathHelpers
  • The Swift subspec adds the Swiftier API to that default subspec
  • HTTPMessage and Mocktail are opt-in subspecs: list them explicitly if you need them
  • OHPathHelpers doesn't depend on Core and can be used independently of OHHTTPStubs altogether
List of all the subspecs & their dependencies

Here's a list of which subspecs are included for each of the different lines you could use in your Podfile:

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' ✅ ✅

Swift Package Manager

OHHTTPStubs is compatible with Swift Package Manager, and provides 2 targets for consumption: OHHTTPStubs and OHHTTPStubsSwift.

  • OHHTTPStubs is equivalent to the OHHTTPStubs subspec.
  • OHHTTPStubsSwift is equivalent to the OHHTTPStubs/Swift subspec.

Note: We currently do not have support for the HTTPMessage or Mocktail subspecs in Swift Package Manager. If you are interested in these, please open an issue to explain your needs.

Carthage

OHHTTPStubs is also compatible with Carthage. Just add it to your Cartfile.

Note: 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.

Using the right Swift version for your project

OHHTTPStubs supports Swift 3.0 (Xcode 8+), Swift 3.1 (Xcode 8.3+), Swift 3.2 (Xcode 9.0+), Swift 4.0 (Xcode 9.0+), Swift 4.1 (Xcode 9.3+), Swift 4.2 (Xcode 10+), Swift 5.0 (Xcode 10.2), and Swift 5.1 (Xcode 11) however we are only testing Swift 4.x (using Xcode 9.1 and 10.1) and Swift 5.x (using Xcode 10.2 AND 11) in CI.

Here are some details about the correct setup you need depending on how you integrated OHHTTPStubs into your project.

CocoaPods: nothing to do

If you use CocoaPods version 1.1.0.beta.1 or later, then CocoaPods will compile OHHTTPStubs with the right Swift Version matching the one you use for your project automatically. You have nothing to do! 🎉

For more info, see CocoaPods/CocoaPods#5540 and CocoaPods/CocoaPods#5760.

Carthage: choose the right version

The project is set up with SWIFT_VERSION=5.0 on master.

This means that the framework on master will build using:

  • Swift 5.1 on Xcode 11
  • Swift 5.0 on Xcode 10.2
  • Swift 4.2 on Xcode 10.1
  • Swift 4.0 on Xcode 9.1

If you want Carthage to build the framework with Swift 3.x you can:

  • either use an older Xcode version
  • or use the previous version of OHHTTPStubs (6.2.0) — whose master branch uses 3.0
  • or fork the repo just to change the SWIFT_VERSION build setting to 3.0
  • or build the framework passing a SWIFT_VERSION to carthage via XCODE_XCCONFIG_FILE=<config file declaring SWIFT_VERSION> carthage build

Special Considerations

Using OHHTTPStubs in your unit tests

OHHTTPStubs is ideal to write unit tests that normally would perform network requests. But if you use it in your unit tests, don't forget to:

  • remove any stubs you installed after each test — to avoid those stubs to still be installed when executing the next Test Case — by calling [HTTPStubs removeAllStubs] in your tearDown method. see this wiki page for more info
  • be sure to wait until the request has received its response before doing your assertions and letting the test case finish (like for any asynchronous test). see this wiki page for more info

Automatic loading

OHHTTPStubs is automatically loaded and installed (at the time the library is loaded in memory), both for:

  • requests made using NSURLConnection or [NSURLSession sharedSession] — thanks to this code
  • requests made using a NSURLSession that was created via [NSURLSession sessionWithConfiguration:…] and using either [NSURLSessionConfiguration defaultSessionConfiguration] or [NSURLSessionConfiguration ephemeralSessionConfiguration] configuration — thanks to method swizzling done here in the code.

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

Known limitations

  • OHHTTPStubs can't work on background sessions (sessions created using [NSURLSessionConfiguration backgroundSessionConfiguration]) because background sessions don't allow the use of custom NSURLProtocols and are handled by the iOS Operating System itself.
  • OHHTTPStubs don't simulate data upload. 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.
  • OHTTPStubs has a known issue with redirects that we believe is an Apple bug. It has been discussed here and here. The actual result of this bug is that redirects with a zero second delay may nondeterministically end up with a null response.

As far as I know, there's nothing we can do about those three limitations. Please let me know if you know a solution that would make that possible anyway.

Submitting to the App Store

OHHTTPStubs can be used on apps submitted on the App Store. It does not use any private API and nothing prevents you from shipping it.

But you generally only use stubs during the development phase and want to remove your stubs when submitting to the App Store. So be careful to only include OHHTTPStubs when needed (only in your test targets, or only inside #if DEBUG sections, or by using per-Build-Configuration pods) to avoid forgetting to remove it when the time comes that you release for the App Store and you want your requests to hit the real network!

License and Credits

This project and library has been created by Olivier Halligon (@aligatr on Twitter) and is under the MIT License.

It has been inspired by this article from InfiniteLoop.dk.

I would also like to thank:

  • Sébastien Duperron (@Liquidsoul) for helping me maintaining this library, triaging and responding to issues and PRs
  • Kevin Harwood (@kcharwood) for migrating the code to NSInputStream
  • Jinlian Wang (@JinlianWang) for adding Mocktail support
  • and everyone else who contributed to this project on GitHub somehow.

If you want to support the development of this library, feel free to Donate. Thanks to all contributors so far!

More Repositories

1

Reusable

A Swift mixin for reusing views easily and in a type-safe way (UITableViewCells, UICollectionViewCells, custom UIViews, ViewControllers, Storyboards…)
Swift
2,999
star
2

OHAttributedLabel

UILabel that supports NSAttributedString
Objective-C
1,511
star
3

Dip

Simple Swift Dependency container. Use protocols to resolve your dependencies and avoid singletons / sharedInstances!
Swift
977
star
4

UIImage-Resize

Category to add some resizing methods to the UIImage class, to resize it to a given CGSize — or fit in a CGSize keeping aspect ratio
Objective-C
352
star
5

OHAutoNIBi18n

Automate the Localization/Translation of your XIB & interface without any additional code nor IBOutlet!
Objective-C
120
star
6

OHAttributedStringAdditions

NSAttributedString Additions that add convenience methods to manipulate attributed strings easily
Objective-C
107
star
7

SourceryTemplates

Some templates to use for Code Generation in Swift with http://github.com/krzysztofzablocki/Sourcery
HTML
99
star
8

OHGridView

View that display cells as a grid. Uses quite the same API as UITableView
Objective-C
71
star
9

OHPDFImage

A library to easily load PDF files as UIImages
Objective-C
56
star
10

Dip-UI

UI Extensions for https://github.com/AliSoftware/Dip
Swift
48
star
11

OHSwipeWheel

A widget to choose between multiple values by swiping an horizontal wheel. This is kinda like a UIPickerView but rolling horizontally and that takes much less space
Objective-C
42
star
12

pprof

Ruby Gem to list, filter, search and print Provisioning Profiles files
Ruby
39
star
13

Xcode-Utils

A set of useful templates, macros, etc. to use with the Apple Developer Tools
Objective-C
32
star
14

OpeningHours

A small iOS app to keep the list of Opening Hours for your local shops you're used to go to
Swift
27
star
15

OHActionSheet

UIActionSheet subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
27
star
16

OHStackView

This class automatically stack its subviews and relayout them when one of them change its size.
Objective-C
25
star
17

OHAlertView-OHActionSheet

This repo is obsolete. Use OHAlertView and OHActionSheet repos now.
Objective-C
21
star
18

OHURLLoader

Class that uses blocks (new to iOS4/OSX 10.6) to make URL requests/downloads much more easier
Objective-C
19
star
19

OHAlertView

UIAlertView subclass that uses blocks to handle its callback (which make the code much more easier and readable)
Objective-C
16
star
20

AliJSONRPC

A JSON-RPC Framework for Cocoa. Supports JSON-RPC 1.0, 1.1 and 2.0
Objective-C
13
star
21

alisoftware.github.io

AliSoftware's Blog "Crunchy Development": making Swift Magic ✨
SCSS
12
star
22

generate-enum-allvalues

Automatically generate a `static let allValues` for your Swift enums
Swift
8
star
23

SWPromisesDemo

A demo project implementing the StarWars API (swapi.co) in Swift with PromiseKit
Swift
8
star
24

FunctionalVCDemo

Demo for the Functional ViewControllers concept in RxSwift
Swift
8
star
25

MagicSwiftNoStrings

Demo project demonstrate some nice patterns to get rid of String-based API using enums, mixins and SwiftGen
Swift
8
star
26

CodeGen-Workshop

This is the repository used for my SwiftAveiro'19 Workshop about Code Generation
Swift
6
star
27

FormWorkflow

A sample project to demonstrate how to use Promises to describe a workflow of Screens/ViewControllers
Swift
6
star
28

ObjcSwitch

A category to allow you to use the "switch/case"-like syntax with NSObjects (and not just integers/enums!)
Objective-C
6
star
29

swift-syntax-linter-demo

A demo project on how to use SwiftSyntax to implement a simple linter detecting specific call sites of a function in your source code
Swift
6
star
30

KeyPathObserver

Execute blocks when a given property changes (this is KVO, the block-style way)
Objective-C
5
star
31

talks

My talks at conferences
5
star
32

CodeGenDemo

Demo project to show the advantages of Code Generation with SwiftGen & Sourcery
Swift
4
star
33

AliSoftware

3
star
34

SwiftDependencyInjectionTest

A test project to play around and explore some Dependency Injection ideas in Swift — This was the POC that led to Dip
Swift
3
star
35

banana-crumb-muffins

This is the recipe for Banana Crumb Muffins, presented as a GitHub repository (one commit for each step of the recipe). Just for fun.
2
star
36

TVShowOrganizer

Ruby
2
star
37

XCAssetsSample

This sample project try to expose a complex case of using multiple assets with multiple targets. Originally created to test CocoaPods/CocoaPods#3263
Objective-C
2
star
38

xcodeplugin

Tools to generate dvtplugin / xcodeplugins especially for PLIST-files structure definitions
Shell
2
star