Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

AliSoftware/OHHTTPStubs

Repository files navigation

PlatformLanguage: Swift-2.x/3.x/4.x/5.xBuild Status

VersionCarthage SupportedSwift Package Manager Supported

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

  • test your apps withfake network data (stubbed from file) andsimulate slow networks, to check your application behavior in bad network conditions
  • writeunit tests that use fake network data from your fixtures.

It works withNSURLConnection,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 alsoread theonline documentation here.

Basic example

In Objective-C
[HTTPStubsstubRequestsPassingTest:^BOOL(NSURLRequest *request) {return [request.URL.hostisEqualToString:@"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 [HTTPStubsResponseresponseWithFileAtPath:fixturestatusCode:200headers:@{@"Content-Type":@"application/json"}];}];
In Swift

This example is using the Swift helpers found inOHHTTPStubsSwift.swift provided by theOHHTTPStubs/Swift subspec orOHHTTPStubs package.

stub(condition:isHost("mywebservice.com")){ _in  // Stub it with our "wsresponse.json" stub file (which is in same bundle as self)letstubPath=OHPathForFile("wsresponse.json",type(of:self))returnfixture(filePath: stubPath!, headers:["Content-Type":"application/json"])}

Note: if you're usingOHHTTPStubs's Swiftier API (OHHTTPStubsSwift.swift and theSwift subspec orOHTTPStubsSwift 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 likeSWHttpTrafficRecorder 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 byOHHTTPStubs (theHTTPMessage format, the simple response boby/content file, and theMocktail format).

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

Compatibility

  • OHHTTPStubs is compatible withiOS5+,OS X 10.7+,tvOS.
  • OHHTTPStubs also works withNSURLSession as well as any network library wrapping them.
  • OHHTTPStubs isfully 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 byOHHTTPStubsSwift.swift.

Updating to Version 9.0+
  • All classes dropped theOH prefix (OHHHTTPStubs ->HTTPStubs,OHHTTPStubsResponse ->HTTPStubsResponse, etc).
  • TheOHPathHelpers class was renamedHTTPStubsPathHelpers.
  • No method and module names were changed.

Installing in your projects

CocoaPods

UsingCocoaPods is the recommended way.

  • If youintend to useOHHTTPStubs from Objective-C only, addpod 'OHHTTPStubs' to yourPodfile.
  • If youintend to useOHHTTPStubs from Swift, addpod 'OHHTTPStubs/Swift' to yourPodfile 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 includesNSURLSession,JSON, andOHPathHelpers
  • TheSwift subspec adds the Swiftier API to that default subspec
  • HTTPMessage andMocktail are opt-in subspecs: list them explicitly if you need them
  • OHPathHelpers doesn't depend onCore and can be used independently ofOHHTTPStubs 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 yourPodfile:

SubspecCoreNSURLSessionJSONSwiftOHPathHelpersHTTPMessageMocktail
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 andOHHTTPStubsSwift.

  • OHHTTPStubs is equivalent to theOHHTTPStubs subspec.
  • OHHTTPStubsSwift is equivalent to theOHHTTPStubs/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 yourCartfile.

Note: TheOHHTTPStubs.framework built with Carthage will includeall features ofOHHTTPStubs turned on (in other words, all subspecs of the pod), includingNSURLSession andJSON support,OHPathHelpers,HTTPMessage andMocktail 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 integratedOHHTTPStubs into your project.

CocoaPods: nothing to do

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

For more info, seeCocoaPods/CocoaPods#5540 andCocoaPods/CocoaPods#5760.

Carthage: choose the right version

The project is set up withSWIFT_VERSION=5.0 onmaster.

This means that the framework onmaster 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 ofOHHTTPStubs (6.2.0) — whosemaster branch uses3.0
  • or fork the repo just to change theSWIFT_VERSION build setting to3.0
  • or build the framework passing aSWIFT_VERSION to carthage viaXCODE_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 yourtearDown 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 usingNSURLConnection or[NSURLSession sharedSession]thanks to this code
  • requests made using aNSURLSession that was created via[NSURLSession sessionWithConfiguration:…] and using either[NSURLSessionConfiguration defaultSessionConfiguration] or[NSURLSessionConfiguration ephemeralSessionConfiguration] configuration — thanks tomethod swizzling donehere in the code.

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

Known limitations

  • OHHTTPStubscan't work on background sessions (sessions created using[NSURLSessionConfiguration backgroundSessionConfiguration]) because background sessions don't allow the use of customNSURLProtocols and are handled by the iOS Operating System itself.
  • OHHTTPStubs don't simulate data upload. TheNSURLProtocolClient@protocol does not provide a way to signal the delegate that data has beensent (only that some has been loaded), so any data in theHTTPBody orHTTPBodyStream of anNSURLRequest, 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 usingOHHTTPStubs.
  • OHTTPStubshas a known issue with redirects that we believe is an Apple bug. It has been discussedhere andhere. 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

OHHTTPStubscan be used on apps submittedon 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 includeOHHTTPStubs when needed (only in your test targets, or only inside#if DEBUG sections, or by usingper-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 bythis 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 toNSInputStream
  • 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 toDonate. Thanks to all contributors so far!

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp