Skip to content

Usage Examples

AliSoftware edited this page Apr 20, 2015 · 41 revisions

Introduction: Reminder about Swift Closures

If you use OHHTTPStubs in Swift, here is a quick reminder about tricks that can be used when using Swift closures.

  • If the last parameter of a Swift function is a closure, we can use trailing closures. Throughout the following examples, we will use that a lot for the last parameter of OHHTTPStubs.stubRequestsPassingTest(,withStubResponse:), calling it as OHHTTPStubs.stubRequestsPassingTest(…) { /* stub response block */ } which is more readable.
  • If the closure is short, we can use shorthand argument names.
  • If a parameter is unused in the body of the closure, we can use the anonymous variable _ as the parameter name instead, to tell Swift not to bother about this parameter.

Simple examples

Stub requests with some given NSData

With the code below, only network requests to host "mywebservice.com" will be stubbed, and they will return a stubbed response containing the data "Hello World!":

// Objective-C
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
  return [request.URL.host isEqualToString:@"mywebservice.com"];
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
  // Stub all those requests with "Hello World!" string
  NSData* stubData = [@"Hello World!" dataUsingEncoding:NSUTF8StringEncoding];
  return [OHHTTPStubsResponse responseWithData:stubData statusCode:200 headers:nil];
}];
// Swift
OHHTTPStubs.stubRequestsPassingTest({
  return request.URL!.host == "mywebservice.com"
}, withStubResponse:{
  let stubData = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)
  return OHHTTPStubsResponse(data: stubData, statusCode:200, headers:nil)
})

Note: it is not recommended to directly return YES in the first block (and thus stub all requests), because third-party frameworks & SDKs (like Crashlytics, etc) may also send requests on their own and you probably don't want them to receive your own stubbed response (which won't make sense for them anyway).

Stub requests with a file

With the code below, the content of a given file in your application bundle will be used as a stub.
We use the OHPathForFile global function provided in OHPathHelpers.h as a convenience to easily create the path to the file in the app's bundle.

This is useful if you have added all your fixtures (stubbed responses for your Unit Tests) in your Xcode project and linked them with your Unit Test target.

// 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"}];
}];
// Swift
// Note: Here we introduce the use of the shorthand parameter $0 for the first closure
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.host == "mywebservice.com"}) { request in
  // Stub it with our "wsresponse.json" stub file
  return OHHTTPStubsResponse(fileAtPath:OHPathForFile("wsresponse.json", self.dynamicType)!
    statusCode:200 headers:["Content-Type":@"application/json"])
}];

You may also put all your fixtures in a custom bundle (let's call it Fixtures.bundle) and then use the helper functions to get it: OHPathForFileInBundle(@"wsresponse.json",OHResourceBundle(@"Fixtures", self.class)).

Note: If you use a lot of fixtures, you may create a convenience macro like #define fixture(x) OHPathForFileInBundle(@ #x ".json",OHResourceBundle(@"Fixtures", self.class)) so you can then simply use fixture(wsresponse.json) in your ObjC code. As Swift does not support macros, there is no real equivalent in Swift.

Stub requests with a JSON object

As it is common for a lot of WebServices to use the JSON format in their response body, OHHTTPStubs comes with a convenience method (defined as a category in OHHTTPStubs+JSON.h) to build a response from a JSON object.

In practice, this convenience method simply use NSJSONSerialization to transform the NSDictionary or NSArray to JSON, and automatically adds the Content-Type: application/json header if there is no Content-Type header defined.

// Objective-C
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
    return [request.URL.host isEqualToString:@"mywebservice.com"];
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
    NSDictionary* obj = @{ @"key1": @"value1", @"key2": @[@"value2A", @"value2B"] };
    return [OHHTTPStubsResponse responseWithJSONObject:obj statusCode:200 headers:nil];
}];

In the following example, in addition to using shorthand parameter $0 in the first closure and using a trailing closure for the last parameter, we also use the anonymous parameter _ as we don't use the NSURLRequest parameter in the closure.

// Swift
// Note: Here we introduce the anonymous parameter '_' in the second closure (as its NSURLRequest parameter is unused in our code)
OHHTTPStubs.stubRequestsPassingTest({$0.URL!.host == "mywebservice.com"}) { _ in
  let obj = ["key1:"value1", "key2":["value2A","value2B"]]
  return OHHTTPStubsResponse(JSONObject: obj, statusCode: 200, headers: nil)
}

Bad and down network

Set request and response time

You can simulate a slow network by setting the requestTime and/or responseTime properties of your OHHTTPStubsResponse. This is useful to check that your user interface does not freeze when you have bad network conditions, and that you have all your activity indicators working while waiting for responses.

You may use the commodity chainable setters responseTime: and requestTime:responseTime: to set those values and easily chain method calls, like we will do in the following examples:

// 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
OHHTTPStubs.stubRequestspassingTest({$0.URL!.host == "mywebservice.com"}) { _ in
  return OHHTTPStubsResponse(JSONObject:someDict, statusCode:200, headers:nil)
    .requestTime(1.0, responseTime: 3.0)
}

OHHTTPStubs will wait requestTime before sending the NSHTTPURLResponse headers, and then start sending chunks of the stub data regularly during the period of responseTime, to simulate the slow network.

In the end, you will only have the full content of your stub data after requestTime+responseTime (time after which the completion block or connectionDidFinishLoading: delegate method will be called).

Note: You can specify a network speed instead of a responseTime by using a negative value. See below.

Using download speed instead of responseTime

When building the OHHTTPStubsResponse object, you can specify a response time (in seconds) so that the sending of the fake response will be spread over time. This allows you to simulate a slow network for example. (see "Set request and response time")

If you specify a negative value for the responseTime parameter, instead of being interpreted as a time in seconds, it will be interpreted as a download speed in KBytes/s. In that case, the response time will be computed using the length of the response's data to simulate the indicated download speed.

The OHHTTPStubsResponse header defines some constants for standard download speeds:

OHHTTPStubsDownloadSpeedGPRS   =    -7 =    7 KB/s =    56 kbps
OHHTTPStubsDownloadSpeedEDGE   =   -16 =   16 KB/s =   128 kbps
OHHTTPStubsDownloadSpeed3G     =  -400 =  400 KB/s =  3200 kbps
OHHTTPStubsDownloadSpeed3GPlus =  -900 =  900 KB/s =  7200 kbps
OHHTTPStubsDownloadSpeedWifi   = -1500 = 1500 KB/s = 12000 kbps

Example:

// Objective-C
return [[OHHTTPStubsResponse responseWithData:[NSData data] statusCode:400 headers:nil]
        responseTime:OHHTTPStubsDownloadSpeed3G];
// Swift
return OHHTTPStubsResponse(data:NSData(), statusCode: 400, headers: nil)
  .responseTime(OHHTTPStubsDownloadSpeed3G)

Simulate a down network

You may also return a network error for your stub. For example, you can easily simulate an absence of network connection like this:

// Objective-C
NSError* notConnectedError = [NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil];
return [OHHTTPStubsResponse responseWithError:notConnectedError];
// Swift
let notConnectedError = NSError(domain:NSURLErrorDomain, code:kCFURLErrorNotConnectedToInternet, userInfo:nil)
return OHHTTPStubsResponse(error:notConnectedError)

Advanced Usage and Tips

Build the test closure/block separately

As the test condition and/or the stubbed responses for multiple stubs can sometimes be very alike, you can create convenience functions to build them.

This is easier to write in Swift, as closures are way straightforward and functions and closures are interchangeable in Swift, so you can write for example:

// Swift
func isSearchRequest(searchTerm: String) -> (NSURLRequest->Bool) {
  return { request in
    let components = NSURLComponents(URL: request.URL!, resolvingAgainstBaseURL: true)
    if components?.host == "mywebservice.com" && components?.path == "/api/search" {
      let queryItems = components?.queryItems as! [NSURLQueryItem]?
      // Search the Query items for value of the first "q=…" parameter
      let q = queryItems?.filter { $0.name == "q" }.first?.value
      return q == searchTerm // Only true if the value of "q=…" is the searchTerm
    } else {
      return false // Not even a "mywebservice.com/api/search" request
    }
  }
}

// Stub search requests for "?q=foo" with a given stub
OHHTTPStubs.stubRequestsPassingTest(isSearchRequest("foo")) { _ in
  return OHHTTPStubsResponse()
}

// Stub search requests for "?q=bar" with another stub
OHHTTPStubs.stubRequestsPassingTest(isSearchRequest("bar")) { _ in
  return OHHTTPStubsResponse()
}

Stack multiple stubs and remove installed stubs

  • You can call stubRequestsPassingTest:withStubResponse: multiple times. It will just add the stubs in an internal list of stubs.

This may be useful to install different stubs in various places in your code, or to separate different stubbing conditions more easily. See the OHHTTPStubsDemo project for a typical example. This may also be used for a fallback stub, as the first stub being installed will only be called if every other stub fails.

When a network request is performed by the system, the stubs are tested in the reverse order that they have been added, the last added stub having priority over the first added ones. The first stub that returns YES for the first parameter of stubRequestsPassingTest:withStubResponse: is then used to reply to the request.

  • You can then remove any given stub with the removeStub: method. This method takes as a parameter the id<OHHTTPStubsDescriptor> object returned by stubRequestsPassingTest:withStubResponse: (Note: this returned object is already retained by OHHTTPStubs while the stub is installed, so you should keep it in a weak variable so it is properly released from memory once removed).
  • You can also remove all stubs at once with the removeAllStubs method.

This last one is useful when using OHHTTPStubs in your Unit Tests, to remove all installed stubs at the end of each of your test case to avoid stubs installed in one test case to be still installed for the next test case.

// Objective-C
- (void)tearDown
{
    [OHHTTPStubs removeAllStubs];
    [super tearDown];
}
// Swift
func tearDown() {
  OHHTTPStubs.removeAllStubs()
  super.tearDown()
}

Name your stubs and log their activation

You can add a name of your choice to your stubs. The only purpose of this is to easily identify your stubs for debugging, like when displaying them in the console.

// Objective-C
id<OHHTTPStubsDescriptor> stub = [OHHTTPStubs stubRequestsPassingTest:withStubResponse:…];
stub.name = @"Stub for text files";
// Swift
weak var stub = OHHTTPStubs.stubRequestsPassingTest() {  }
stub.name = "Stub for text files"

You can even imagine applying the .name = ... affectation directly (if you don't need to use the returned id<OHHTTPStubsDescriptor> otherwise), for a more concise syntax:

// Objective-C
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
   ...
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
   ...
}].name = @"Stub for text files";
// Swift
OHHTTPStubs.stubRequestsPassingTest() { _ in
  
}.name = "Stub for text files"

You can then list all the installed stubs using [OHHTTPStubs allStubs] (ObjC) / OHHTTPStubs.allStubs() (Swift), which returns an array of objects conforming to OHHTTPStubsDescriptor so you can display their name on the console. This is useful to check that you didn't forget to remove some previous stubs that are still installed for example.

You can also setup a block that gets executed each time a request has been stubbed, using onStubActivation: method. This is typically useful to log the stub being used for each request:

// Objective-C
[OHHTTPStubs onStubActivation:^(NSURLRequest *request, id<OHHTTPStubsDescriptor> stub) {
    NSLog(@"%@ stubbed by %@.", request.URL, stub.name);
}];
// Swift
OHHTTPStubs.onStubActivation() { (request: NSURLRequest, stub: OHHTTPStubsDescriptor) in
  println("\(request.URL!) stubbed by \(stub.name).")
}