-
Notifications
You must be signed in to change notification settings - Fork 602
Contributors Examples
In case you haven't read it already, you can find some "official" usage examples in this wiki page, showing short snippets and specific use cases.
But if you're looking for more in-depth examples or what people do with this library, or want to share how you use OHHTTPStubs
in your project or the configuration you use, feel free to enrich this wiki page to share your own examples with the community.
Feel free to edit this page to add your own examples there
There's a lot of Open-Source projects using OHHTTPStubs
, so the first thing I'd suggest you to do if you want to see how people use OHHTTPStubs
in actual projects is to simply do a search on GitHub about it. You'll find plenty of examples to start with there!
Even though OHHTTPStubs
is used by a lot of people mainly to write Unit Tests, where things have to be pretty deterministic, it's also useful to use OHHTTPStubs
in your actual application target to simulate a server, either because the real server or endpoint is still being developed and isn't ready yet, or because you have to do a demo of your application but are not sure you're gonna have any network in the room or conference where you're doing the demo.
In those cases, it could then also be nice to simulate real network conditions, where you can have random network failures but only some of the time. It's then nice to randomise the responses returned by your stubs to integrate random errors there to be more realising.
Here's a snippet of how you can achieve such effect:
stub(condition: …) { _ in
/// Create some Chaos!
switch Int(arc4random_uniform(20)) {
case 1:
let notConnectedError = NSError(domain: NSURLErrorDomain, code: URLError.notConnectedToInternet.rawValue, userInfo: nil)
return OHHTTPStubsResponse(error: notConnectedError)
case 2:
let timeOutError = NSError(domain: NSURLErrorDomain, code: URLError.timedOut.rawValue, userInfo: nil)
return OHHTTPStubsResponse(error: timeOutError)
case 3:
let unavailable = NSError(domain: NSURLErrorDomain, code: URLError.cannotConnectToHost.rawValue, userInfo:nil)
return OHHTTPStubsResponse(error: unavailable)
default:
// But most of the time return the valid stubbed data instead of simulating an error
let stubPath = OHPathForFile("my-stub.json", type(of: self))!
return fixture(filePath: stubPath, headers: ["Content-Type":"application/json"])
}
}
Here's a gist by @wwe-johndpope showing:
- the usage of a dictionary to list the absolute URLs to stub and their corresponding local JSON files to stub the request with
- the use of Swagger APIs to get examples from a Swagger documentation and use them as stubs for your requests