Git Product home page Git Product logo

ohhttpstubs's Introduction

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!

ohhttpstubs's People

Contributors

417-72ki avatar adamsousa avatar alisoftware avatar ashton-w avatar attheodo avatar c1ira avatar corinnekrych avatar derlobi avatar hpique avatar ikesyo avatar indragiek avatar ishkawa avatar jeffctown avatar jinlianwang avatar jzucker2 avatar kcharwood avatar liquidsoul avatar manicmaniac avatar maxgabriel avatar morrowa avatar mrkite avatar mxcl avatar ndonald2 avatar nsprogrammer avatar pimnijman avatar sberrevoets avatar simon-kaz avatar thii avatar tibr avatar victorg1991 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ohhttpstubs's Issues

Stubbing two requests in a single test case

One issue I've been running into lately has been when I want to test the process of multiple requests in a single test case. An example of this would be testing successfully unregistering from a server. First I want to simulate successfully registering with a server stubbing the response with a 200 and some JSON, and once that is done I want to stub the response with another 200 response and different JSON and then send the unregister request.

I have a helper function I call in each test so I can quickly stub a response with a single line of code:

- (void)stubResponseWithStatusCode:(int)statusCode dictionary:(NSDictionary *)responseDictionary delay:(NSTimeInterval)delay {
    [OHHTTPStubs removeLastStub];

    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return YES;
    } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
        return [[OHHTTPStubsResponse responseWithJSONObject:responseDictionary statusCode:statusCode headers:nil] responseTime:delay];
    }];
}

EDIT: I've updated my current async testing strategy to take advantage of the XCTestExpectation APIs after reading your docs, rather than implement my own method, and the problem still exists.

When I stub a response without any delay in the beginning of the test, send the request, and inside the completion block when the request is successful stub the NEXT request with a new response without any delay, there are times where the second response is never received, so the tests fail when they hit the 2-4 second timeout. Is this something you've seen before, a known issue, or operator error? Thanks!

OHHTTPSTubs interfering with Task countOfBytesSent

When I have a stubbed method the countOfBytesSent seems to strip the content length and even prevent countOfBytesSent from being updated for a nsurlsessiontask.

Removing the stubs however causes it to work perfectly.

Problems with iOS 7.1 and Swift

Xcode 6.2
OHHTTPStubs 3.1.11
CocoaPods 0.36.1

Tried to run tests on iOS 7.1 simulator in a Swift project and it doesn't work:
Obs. 1: on iOS 8.1 simulator works fine
Obs. 2: run pod without use_frameworks! config, because I want to support iOS 7

IDEBundleInjection.c: Error 3588 loading bundle '/Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator/UITests.xctest': The bundle “UITests” couldn’t be loaded.
DevToolsBundleInjection environment:
XCInjectDiagnostics: (null)
XCInjectBundleInto: /Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator/myapp.app/myapp
XCInjectBundle: /Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator/UITests.xctest
TestBundleLocation: /Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator/UITests.xctest
TMPDIR: /Users/me/Library/Developer/CoreSimulator/Devices/7B46887A-C6CF-468B-8AD5-C526D8D095D4/data/Applications/799AB217-E68E-44C7-8422-60BEE1F2A0E6/tmp
DYLD_LIBRARY_PATH: /Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator
DYLD_INSERT_LIBRARIES: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/IDEBundleInjection.framework/IDEBundleInjection
DYLD_FRAMEWORK_PATH: /Users/me/Library/Developer/Xcode/DerivedData/myapp-cypnccujdzumvjcxeuymxljgxetv/Build/Products/Debug-iphonesimulator
DYLD_FALLBACK_LIBRARY_PATH: /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 7.1.simruntime/Contents/Resources/RuntimeRoot/usr/lib
DYLD_FALLBACK_FRAMEWORK_PATH: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks

Add iOS7.1 target to the Travis compilation matrix

We should improve that .travis.yml configuration, because I think it could be interesting to run the Unit tests both with destination OS=7.1 and OS=8.1

Especially, some issues did arise in the past due to modifications in iOS8, and I had to fix them by ensuring both that it adapts to the new behavior of iOS8… while still working on iOS7.
That was the case for #65 and #82 (issues both introduced by changes in iOS8)

So we should ensure both that it works on iOS8 while it does not introduce regressions on iOS7.

For reference, this consists of adding some lines to .travis.yml and varying the configurations used in the -destination parameter, like: -destination 'platform=iOS Simulator,name=iPhone 6,OS=…'

Body of request never makes it to stubRequestPassingTest:

I use OHHTTPStubs to test if my AFHTTPRequest send the correct xml as body in a request. This works fine and all tests pass, checking the body that would be sent in the stubRequestPassingTest:

Now I moved to using AFHTTPSessionManager, and the program still works fine, but the tests fail, telling me that the body to be sent is empty, instead of the expected xml.

Something funny that happens: the request that gets prepared by my program has a different pointer (0xe1efbc0) than the request (0xe2c3310) that is checked in the stub. Any idea what is going on? Is it possible the requests gets copied, but the body didn't make it to the copy?

Here is a log from my console:

2014-02-06 14:09:36.278 xctest[69495:303] Posting request 0xe1efbc0 with body:
2014-02-06 14:09:36.278 xctest[69495:1903] Stubbing url /admin/_cmdstat.jsp
2014-02-06 14:09:36.278 xctest[69495:1903] checking body of request 0xe2c3310
2014-02-06 14:09:36.279 xctest[69495:1903] Would sent body:
/Volumes/InternalHD/Projecten/ZoneDirectorViewer/ZoneDirectorViewer/Connection/ServerConnectionTests.m:551: error: -[ServerConnectionTests testGetSystemInfo] : ((requestedBody) equal to (expectedBody)) failed: ("") is not equal to ("")

Can't get OHHTTPStubs to work with NSURLSession (Bug?)

I'm trying to use OHHTTPStubs in my XCTest class,

This is how I configured OHTTPStubs in my test file.

//
// Tests Configuration
//
- (void)setUp
{
    [super setUp];
    _bundle = [NSBundle bundleForClass:[self class]];
    [self configureHTTPStubs];
    [self installHTTPStubs];
}

- (void)configureHTTPStubs
{
    [OHHTTPStubs onStubActivation:^(NSURLRequest *request, id<OHHTTPStubsDescriptor> stub) {
        NSLog(@"[OHHTTPStubs] Request to %@ has been stubbed with %@", request.URL, stub.name);
    }];
}

- (void)installHTTPStubs
{
    HIAPIRequests *requester = [[HIAPIOperator sharedOperator] requester];
    [OHHTTPStubs setEnabled:YES forSessionConfiguration:requester.session.configuration];
    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return [request.URL.path isEqualToString:@"/image_upload"];
    } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
        return [[OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"image_upload_ws_response.json", nil)
                                                 statusCode:201
                                                    headers:@{@"Content-Type":@"text/json"}] responseTime:OHHTTPStubsDownloadSpeed3G];
    }].name = @"Image Upload OK";

}

//
// In my Requester class this is how I setup the NSURLSession configuration
//
- (void)configureURLSession
{
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    _session = [NSURLSession sessionWithConfiguration:config];
}

And this is how I'm performing a request

- (void)uploadImage:(UIImage *)image
    completionBlock:(operationCompletionBlock)completionBlock
      progressBlock:(operationProgressBlock)progressBlock
{
    NSData *imageData = UIImageJPEGRepresentation(image, 0.80);
    NSURLRequest *request = [NSURLRequest requestWithURLString:@"/image_upload"];
    NSURLSessionUploadTask *uploadTask = [_session uploadTaskWithRequest:request
                                                            fromData:imageData
                                                   completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                       completionBlock(data, error);
                                                   }];

    [_progressTable setObject:progressBlock forKey:uploadTask];
    [uploadTask resume];
}

In the completionHandler callback I'm basically getting a no domain found error (error NSURLError * domain: @"NSURLErrorDomain" - code: -1003 0x08a70740) , @"A server with the specified hostname could not be found."

I'm completely sure that I'm querying the correct URL (the one I stubbed with OHHTTPStubs) in my test.

What could be going on here? Bug maybe?

Not able to stub requests

Hey there,

OHHTTPStubs is failing to stub any request at all for me. I integrated OHHTTPStubs manually into my project and all my requests seem to hit the network. Maybe the method Swizzling that worked before to auto enable OHHTTPStubs is now broken?

Here's a self contained project with a single test case to explain my issue.

Am I doing something wrong?

Thanks!

Never calling the stub

Hi, I tried to implement stubs on xcode 5 with afnetworking 2.0 and it is not working. My current version of OHHTTPStubs pod is 3.0.0

  [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
    return YES;
  }
     withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
                        return [[OHHTTPStubsResponse alloc] init];
                      }];

I am actually using an AFHTTPSessionManager singleton configured:

+ (instancetype)sharedInstance
{
  static APTHttpClient *_sharedClient = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    _sharedClient = [[APTHttpClient alloc] initWithBaseURL:[NSURL URLWithString:APRProductionServer] sessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  });

  return _sharedClient;
}

This is the method I am actually calling after the stub:

- (void)getContacts
{
  [self GET:@"/contacts"
 parameters:nil
    success:^(NSURLSessionDataTask *task, id responseObject) {
      NSLog(@"%@",responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
      NSLog(@"Error: %@", error.userInfo);
    }];
}

Is there something I am doing wrong?

Bug? responseWithError: method of OHHTTPStubsResponse class

+(OHHTTPStubsResponse*)responseWithError:(NSError*)error
{
    OHHTTPStubsResponse* response = [[self  alloc] initWithError:error];
#if ! __has_feature(objc_arc)
    [response release]; <------------ Why?
#endif
    return response;
}

You should use "autorelease" instead of "release"?

OHHTTPStubs does not work with synchronous requests

When using [NSURLConnection sendSynchronousRequest:... returningResponse:... error:...] the stub does not respond and the request reaches timeout.

This is because the startLoading implementation of the private NSURLProtocol used by OHHTTPStubs uses dispatch_after(dispatch_get_main_queue(), …) so if the main thread is frozen while waiting for the request response, the code will not be dispatched (at least not until the main thread stop waiting for the request and timeout and continue running)

A fix is being studied and will hopefully be released soon

Thanks @QuentinArnault for informing me about this issue

Correct way to stub HTTP requests when doing Application Tests with KIF

Hey!

OHHTTPStubs is obviously super awesome and I use it for my unit tests, but now I'm starting to do application tests with KIF and would like to stub out those connections. What are the best practices for doing that? I know I could put the code in my didFinishLaunchingWithOptions: method, but then it also happens when you are running the application locally. Currently I've hacked it and put it in the KIFTestActor load method, and I was thinking of creating an OHHTTPStubs `load method to put it in. Any ideas?

Not working on Travis anymore?

Our Travis tests started failing when building OHHTTPStubs.
Are you aware of any issues with Travis popping up recently?
It worked 2 days ago - same code failed today.

We have a pod file with this:

platform :ios, '6.0'

target 'GA-SDK-IOS-Tests' do
pod "OHHTTPStubs", "~> 3.1.9"
pod "OCMock", "~> 2.2.4"
pod "XCAsyncTestCase", "~> 1.0.0"
end

Works fine locally with pod install and running tests in Xcode

But started getting this error from Travis:

Failures:
  0) Compile /Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs+NSURLSessionConfiguration.m
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
CompileC /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Objects-normal/i386/OHHTTPStubs+NSURLSessionConfiguration.o OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs+NSURLSessionConfiguration.m normal i386 objective-c com.apple.compilers.llvm.clang.1_0.compiler
    cd /Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods
    export LANG=en_US.US-ASCII
    export PATH="/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode.app/Contents/Developer/usr/bin:/Users/travis/.rvm/gems/ruby-2.0.0-p481/bin:/Users/travis/.rvm/gems/ruby-2.0.0-p481@global/bin:/Users/travis/.rvm/rubies/ruby-2.0.0-p481/bin:/Users/travis/.rvm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin"
    /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang -x objective-c -arch i386 -fmessage-length=0 -fdiagnostics-show-note-include-stack -fmacro-backtrace-limit=0 -std=gnu99 -fmodules -fmodules-cache-path=/Users/travis/Library/Developer/Xcode/DerivedData/ModuleCache -fmodules-prune-interval=86400 -fmodules-prune-after=345600 -Wnon-modular-include-in-framework-module -Werror=non-modular-include-in-framework-module -Wno-trigraphs -fpascal-strings -O0 -Wno-missing-field-initializers -Wno-missing-prototypes -Wno-implicit-atomic-properties -Wno-receiver-is-weak -Wno-arc-repeated-use-of-weak -Wno-missing-braces -Wparentheses -Wswitch -Wunused-function -Wno-unused-label -Wno-unused-parameter -Wunused-variable -Wunused-value -Wempty-body -Wuninitialized -Wno-unknown-pragmas -Wno-shadow -Wno-four-char-constants -Wno-conversion -Wconstant-conversion -Wint-conversion -Wbool-conversion -Wenum-conversion -Wshorten-64-to-32 -Wpointer-sign -Wno-newline-eof -Wno-selector -Wno-strict-selector-match -Wundeclared-selector -Wno-deprecated-implementations -DDEBUG=1 -DDEBUG=1 -DCOCOAPODS=1 -DXCODE_VERSION=0600 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator7.1.sdk -fexceptions -fasm-blocks -fstrict-aliasing -Wprotocol -Wdeprecated-declarations -g -Wno-sign-conversion -fobjc-abi-version=2 -fobjc-legacy-dispatch -mios-simulator-version-min=6.0 -iquote /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-generated-files.hmap -I/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-own-target-headers.hmap -I/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-all-target-headers.hmap -iquote /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-project-headers.hmap -I/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Products/Debug-iphonesimulator/include -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Build -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Build/OHHTTPStubs -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Public -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Public/OCMock -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Public/OHHTTPStubs -I/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/Headers/Public/XCAsyncTestCase -I/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/DerivedSources/i386 -I/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/DerivedSources -F/Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Products/Debug-iphonesimulator -fobjc-arc -DOS_OBJECT_USE_OBJC=0 -include /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/PrecompiledHeaders/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-prefix-anzycpslnrdwpddfyxybytibxgfg/Pods-GA-SDK-IOS-Tests-OHHTTPStubs-prefix.pch -MMD -MT dependencies -MF /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Objects-normal/i386/OHHTTPStubs+NSURLSessionConfiguration.d --serialize-diagnostics /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Objects-normal/i386/OHHTTPStubs+NSURLSessionConfiguration.dia -c /Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs+NSURLSessionConfiguration.m -o /Users/travis/Library/Developer/Xcode/DerivedData/GA-SDK-IOS-boftlfbvtexntphfgrniugydxlym/Build/Intermediates/Pods.build/Debug-iphonesimulator/Pods-GA-SDK-IOS-Tests-OHHTTPStubs.build/Objects-normal/i386/OHHTTPStubs+NSURLSessionConfiguration.o
In file included from /Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs+NSURLSessionConfiguration.m:14:
In file included from /Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs.h:30:
/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubsResponse.h:186:88: error: expected ':'
                           headers:(NSDictionary*)httpHeaders NS_DESIGNATED_INITIALIZER;
                                                                                       ^
                                                                                       :
/Users/travis/build/GameAnalytics/GA-SDK-IOS/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubsResponse.h:217:71: error: expected ':'
-(instancetype)initWithError:(NSError*)error NS_DESIGNATED_INITIALIZER;
                                                                      ^
                                                                      :
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
** BUILD FAILED ** (10589 ms)
The command "xctool -workspace GA-SDK-IOS.xcworkspace -scheme GA-SDK-IOS-Tests -sdk iphonesimulator7.1 build test" exited with 1.
Done. Your build exited with 1.

iOS7 NSURLSessionDataTask support

The library is not working with AFNetworking 2.0.0 RC3, which uses the new NSURLSessionDataTask. Are there any plans on getting the library to work with the new NSURLSession-style library?

Here's an example which is not working

#import <XCTest/XCTest.h>
#import <OHHTTPStubs/OHHTTPStubs.h>
#import <AFNetworking/AFHTTPSessionManager.h>

// A couple of macros for dealing with async blocks
#define TestNeedsToWaitForBlock() __block BOOL blockFinished = NO
#define BlockFinished() blockFinished = YES
#define WaitForBlock() while (CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0, true) && !blockFinished)


@interface NSURLSessionDataTaskStubTest : XCTestCase
@end


@implementation NSURLSessionDataTaskStubTest

- (void)testFailingExample
{
    // Setup stub
    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return YES;
    } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {

        NSString * json_str = @"{ \"suggestions\" : \"schmugestion\" }";

        NSData* stubData = [json_str dataUsingEncoding:NSUTF8StringEncoding];
        return [OHHTTPStubsResponse responseWithData:stubData statusCode:200 headers:nil];
    }];


    TestNeedsToWaitForBlock();

    // Make the http call
    AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:9494"]];
    NSMutableURLRequest *request = [client.requestSerializer requestWithMethod:@"GET" URLString:@"/public/suggestions/search" parameters:nil];

    NSURLSessionDataTask *task = [client dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        XCTAssertNil(error, @"Should be no error if the stubbing worked");
        BlockFinished();
    }];

    // Start getting data and wait for the block to be called
    [task resume];
    WaitForBlock();

    [OHHTTPStubs removeAllStubs];
}

@end

Background NSURLSession error

Hello,

I keep getting the following failure in my test despite the fact that I have stubbed the HTTP request:

Application must have a bundle identifier to use a background NSURLSession

Any idea how I could use OHHTTPStubs with Background NSURLSession ? Is that supported ?

Stubs request tests pass, but stubs response block not called

Hi,

Here's my setup for the stubbing:

id<OHHTTPStubsDescriptor> stub = [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {

    return [request.URL.absoluteString containsString:kVisitReviewPath];

} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {

    return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"patient_visit_review.json",nil)
                                            statusCode:200
                                               headers:@{@"Content-Type":@"text/json"}];
}];

This test is being passed multiple times (I'm breaking on firstStubPassingTestForRequest: and foundStub always contains the exact OHHTTPStubsDescriptor I'm expecting); however, the stub response block never gets called.

Here's what I've verified so far, based on reading the Github Issue history of this repo:

  1. setEnabled: gets called with YES, so OHHTTPStubsProtocol gets registered
  2. I'm using AFNetworking 2.0, and NSURLSession is initialized with [NSURLSessionConfiguration defaultSessionConfiguration]
  3. There is only one singleton instance of OHHTTPStubs being used

Does anyone have any idea where I can look next to keep debugging?

Conditional stub responses

Hey Olivier

I'm trying to use the request in the responseRequests: method to do some conditional stubs in order to create the OHHTTPStubsResponse, I'm trying to get the parameters from a POST request that is generated with AFNetworking 2 but the httpbody is nil...

This is the right way to create conditional responses?

stubs not being activated when other tests are run.

Using AFNetworking2, Specta for tests and Expecta for matching. Xcode5.

I have tests for the network in one file which uses OHHTTPStubs. When I run the tests for just that file, then the stubs are called and the request doesn't go out to the network.

But, if I run all tests (CMD + U) then the stubs are not activated and the request goes out to the network.

I'm going nuts and I'm wondering if I've missed anything.

Problems when declaring stubs in app and in tests

Hi,

I use OHHTTPStubs for two things:

  1. Stub network related code in tests with Kiwi
  2. Stub network related code in my app for Web Services not implemented yet

I encounter an issue, demonstrated with the sample available here: OHHTTPStubs seems to not detect the two stubs I declared, one in my app delegate, the other one in my tests. Only one of them is available in the tests while I expect to be able to use both (in my sample project, only the one declared in the tests is available in the tests, while in another project this is the opposite).

I guess I am not using OHHTTP the right way. I would appreciate if you could let me know if I am doing something wrong or if this is an known limitation, or any other thing.

Thanks.

OHHTTPStubs not working with iOS8 & Swift

Hi all,

I am trying to use OHHTTPStubs under Swift on iOS 8. Not sure what I am doing wrong but so far was unable to make it work. Here is exempt of the code that setup's the stub

 OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest!) -> Bool in
     return true
}, withStubResponse:( { (request: NSURLRequest!) -> OHHTTPStubsResponse in
    return OHHTTPStubsResponse(data:NSData.data(), 
                                             statusCode: 200, headers: ["Content-Type" : "text/json"])
}))

// initialize NSURLSession and make request

Unfortunately the stub is not called making the test fail with a 404. Am i doing sth wrong or the lib not yet supported on iOS 8 (presumably sth has changed there) ?

Regards

Query parameters are not present in request.URL

When using

OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
  return [request.URL isEqual:expectedURLWithQueryParameters];
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
  NSString* fixture = OHPathForFileInBundle(@"SuccessfullLogin.json",nil);
   return [OHHTTPStubsResponse responseWithFileAtPath:fixture statusCode:200 headers:@{@"Content-Type":@"application/json"}];
}];

I've noticed that if the the query parameters do no appear in the request.URL but when performing the real request the query parameter are sent to the server. (I'm using AFNetworking).

In my code if I am doing a request like this:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:@{@"param1":@"value1"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

A GET request to http://example.com/resources.json?param1=value is perform but when the HTTP request is stubbed the request.URL is just http://example.com/resources.json

Ability to play nice with VCR recorders.

Hello,

I wanted to know if someone is interested in bringing the ability to stub the responses from a source file previously recorded by some VCR tool like VCRURLConnection into OHHTTPStubs?

Stubbing a couple of requests/responses using current OHHTTPStubs API always worked great for me for unit testing, but it became a more difficult task to have the whole test suite stubbed when I began writing acceptance tests.

I am personally interested in this because I sometimes want to do acceptance/integration testing of my app but without hitting a network at all.

This is the typical structure of HTTP request/response pair recorded by VCRURLConnection:

[
  {
    "method" : "GET",
    "status" : 200,
    "body" : "iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAABSUlEQVQoz5WSMWsC\r\nQRCF3+6JBnvhQEERi5BKyD9IqeY3BEkRbNQmVQ47SZHisJIUIqktTkjS5gcIh1aS\r\nQkEkgmDtoiL30uwaCSGc0+3s+2Z2Z54gmQXwACCPcDEC0BQkOydAB1iQ9AHgulQ8\r\nD0O8vr1\/AkBsVgpJcvlm1wikdjp1FgCGAKA67Zm\r\nlrSCeq2a+d2lXqtmLGkFrtua6dRQAADJJwBXy+UyUqnc5WLRWJBMJTcAsPhanG13\r\nW9luP09s294D+BBC3Etd4RHAwLbtveM05kopSRIkoZSSjtOYa2igtT9BMkWyR9Lv\r\ne960VCysS8XCuu95U5K+vkv9OTGSWS3yDWjOet+HkEdAB0Dvn030SHZMAfPHsM7J\r\nay3MVEOZwCxfCHFpwFNsNxJC3JqnNrV5QxkcAL4BuO+udFY5258AAAAASUVORK5C\r\nYII=",
    "headers" : {
      "Expires" : "Wed, 21 May 2014 17:09:52 GMT",
      "Last-Modified" : "Thu, 01 Dec 2011 10:50:05 GMT",
      "Server" : "nginx\/0.7.67",
      "Content-Type" : "image\/png",
      "Content-Length" : "386",
      "Connection" : "keep-alive",
      "Date" : "Tue, 21 May 2013 17:09:52 GMT",
      "Cache-Control" : "max-age=31536000",
      "Accept-Ranges" : "bytes"
    },
    "uri" : "http://someuri"
  },
  /* more request/responses */
]

I think it can be pretty easy to create a some sort of plugin for OHHTTPStubs, so it could perform a reading of the stuff to be stubbed from a VCRURLConnection's cassettes.

I am sure that with time I will run into this effort of pairing OHHTTPStubs with VCRURLConnection , I just want to know, if someone else is interested in such product as I do.

What do you think?

Stubs not called for requests sent by RestKit

Hi,

I have a few tests using OHHTTPStubs in my project, and some of them fail because the stub is not called. I know they are not called because a breakpoint on the response block does not pause the execution, and because RestKit complains about the fake URL.

I'm using OHHTTPStubs 3.1.2 installed via CocoaPods, RestKit 0.9.3 (quite old but updating is not possible right now), iOS 7.1 and XCode 5.1.1.

Here's the code of one test that fails:

- (void)testRetrievePlatformInfo
{   
    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return YES;
    } withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
        return [OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(@"PlatformInfoResponse-4.0.json", nil) statusCode:200 headers:[NSDictionary dictionaryWithObject:@"application/json" forKey:@"Content-Type"]];
    }].name = @"Platform Information";

    [loginProxy retrievePlatformInformations];

    NSLog(@"All stubs: %@", [OHHTTPStubs allStubs]);

    // Wait for the asynchronous code to finish, or a 5s timeout
    NSDate* timeoutDate = [NSDate dateWithTimeIntervalSinceNow:5];
    responseArrived = NO;
    while (!responseArrived && ([timeoutDate timeIntervalSinceNow]>0))
        CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.01, YES);

    // some assertions
}

The line

[loginProxy retrievePlatformInformations];

calls this method

- (void)retrievePlatformInformations {
    RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:[self createBaseURL]];
    [RKObjectManager setSharedManager:manager];

    RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[PlatformServerVersion class]];
    [mapping mapKeyPathsToAttributes:
     @"platformVersion",@"platformVersion",
     @"platformRevision",@"platformRevision",
     @"platformBuildNumber",@"platformBuildNumber",
     @"platformEdition",@"platformEdition",
     nil];

    [manager loadObjectsAtResourcePath:@"platform/info" objectMapping:mapping delegate:self];          
}

Displaying the registered stubs shows that it is OK so far:

2014-06-09 17:42:27.959 eXo[30966:60b] All stubs: (
    "<OHHTTPStubsDescriptor 0x9507da0 : Platform Information>"
)

My test class implements delegate methods for handling the response, one for success and one for error. Indeed the error method is called immediately:

2014-06-09 17:42:29.714 eXo[30966:60b] C restkit.network:RKRequest.m:349 SharedClient = <RKClient: 0x9815e90> and network availability = 0
2014-06-09 17:42:50.687 eXo[30966:60b] ERROR: Error Domain=com.twotoasters.RestKit.ErrorDomain Code=2 "The client is unable to contact the resource at http://demo.platform.exo.org/rest/platform/info" UserInfo=0x9816560 {NSLocalizedDescription=The client is unable to contact the resource at http://demo.platform.exo.org/rest/platform/info}

Elsewhere in the code I am logging when stubs are activated

[OHHTTPStubs onStubActivation:^(NSURLRequest *request, id<OHHTTPStubsDescriptor> stub) {
        NSLog(@"%@ request stubbed (%@ %@)", stub.name, request.HTTPMethod, request.URL);
    }];

and surely nothing is logged.

Although RestKit is based on NSURLConnection, when I test another method which sends a request with NSURLConnection directly, this request is stubbed properly...

Finally, I have checked the similar issues #37 #42 and #47 , simplified my Podfile to the maximum, etc but it didn't help.

I am clueless, I might isolate the test case in a separate project for you to see the whole picture, and start upgrading RK if that helps, but meanwhile any idea on this issue would be appreciated.

Cheers,
Philippe

Delegate methods for NSURLSessionTaskDelegate not getting called?

Should they be getting called ?

I would like to be able to get the 'upload progress' of an image, but not sure if OHHTTPStubs can do that.

This is what I'm trying to do, it's crazy that none of the delegate methods are getting called though, we should at least hit the completion handler.

// Upload Image

- (void)uploadImage:(UIImage *)image
    completionBlock:(operationCompletionBlock)completionBlock
      progressBlock:(operationProgressBlock)progressBlock
{
    NSData *imageData = UIImageJPEGRepresentation(image, 0.80);
    NSURLRequest *request = [NSURLRequest requestWithURLString:@"/image_upload"];
    NSURLSessionUploadTask *uploadTask = [_session uploadTaskWithRequest:request
                                                                fromData:imageData
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           if (completionBlock) {
                                                               NSError *err;
                                                               NSDictionary *d = [NSJSONSerialization JSONObjectWithData:data options:0 error:&err];
                                                               completionBlock([HIImageData imageDataFromJSONRepresentation:d], error);
                                                           }
                                                       }];

    [_progressTable setObject:progressBlock forKey:uploadTask];
    [uploadTask resume];
}


// From <NSURLSessionTaskDelegate>  (Not Getting Called)
- (void)URLSession:(NSURLSession *)session
              task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
    operationProgressBlock completionBlock = [_progressTable objectForKey:task];

    if (completionBlock) {
        completionBlock(totalBytesSent/totalBytesExpectedToSend);
    }
}

// From <NSURLSessionTaskDelegate>  (Not Getting Called)
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    [_progressTable removeObjectForKey:task];
}

Switch to XCTests

This conversion from OCUnit to XCTest was waiting for a long time, especially because:

  • I wanted to keep the support for Xcode4 during the transition last year
  • OHHTTPStubs can target earlier iOS versions, and we should still be able to test on iOS versions not supporting NSURLSessions for example to check that it compiles and works correctly in such older OSes… but those older deployment targets dont support XCTest (the XCTest framework and especially its bundled executable that Xcode runs to execute the XCTests is not present in earlier simulators and the tests won't be able to launch at all)

Moreover, it seems that, with the cumulative migrations from earlier Xcode versions, my Unit Test target is somehow corrupted or whatnot, making the "Automatic Migration" to XCTest using the Xcode assistant not working properly to its whole extent (missing XCTest framework, odd unstable state after automatic migration, …) and leading to an incomplete migration.


But with Xcode6 coming, and OCUnit being not officially deprecated, we will really have to migrate eventually.

Note: Given that the automatic migration leaves some odd failures and strange states, I'll probably create a brand new Unit Tests target — or even maybe a brand new Xcode project/workspace ?!) and reimport my files in there, to start with a clean slate instead of risking importing all those corruptions that seems to have been introduced by previous migrations).
So this task will not be as simple as using the automatic assistant
😒


During that migration, I'll also migrate my asynchronous testing to use the new XCTestExpectations too — and using a custom implementation with the same API as Apple's for users still running Xcode5, at least during the transition from Xcode5 to Xcode6, so that it will be a transparent migration).

OHHTTPStubs not responding with data

I'm just starting using OHHTTPStubs in my unit tests and have the most basic scenario - mocking http synchronous request. Here is the code:

[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest request) {
NSLog(@"Setting host for OHHTTPStub of %@", self.escrowHost);
return [request.URL.host isEqualToString:self.escrowHost];
} withStubResponse:^OHHTTPStubsResponse
(NSURLRequest *request) {
NSLog(@"Setting response for the 200 success escrow call");
NSString *jsonString = @"{"key":"value"}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
return [OHHTTPStubsResponse responseWithData:data statusCode:200 headers:nil];
}];

Crazy thing is - this code worked great yesterday, but not today. My code has not changed. What else could be a factor?
Here is the simple GET sync call:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseCode error:&error];

responseData is coming as nil. Any help will be appreciated. Thank you!

Unset request handler

First of all, thanks for the OHHTTPStubs - it is very handy to use and works great!

I wonder if the possibility to unset request handlers could be added to OHHTTPStubs.

I haven't test this yet, but I suspect that mock responses written in different test files could begin to interfere with each other.

Having such functionality obviously would assume setting up request handlers in setup blocks and unsetting them in teardown blocks.

Thanks!

Interfering with push notification registration

I found this library very useful, however, I want to point out that when this library is simply included in a project the +(void)load method in NSURLSessionConfiguration(OHHTTPStubsSupport) is called. This interferes with things like Amazons SDK and registering for push notifications even when none of the header are included or any of the methods used. The docs mention to use this code as part of a test target or use it in #if DEBUG. Using it in #if DEBUG statements is not enough. The swizzling still occurs and can create very hard to track down issues with other networking code. In my case Amazon SDK networking calls and registering for push notifications were simply not working after any of my own networking calls. My solution was to completely remove the source from my project. It's a really nice tool to have. Perhaps a way to have it play nicely when not in use and without having to remove it from my code or maintain another target would be very helpful. I'm sorry I don't have a code sample. Perhaps I can get something soon. It's not straight forward as I was only having issues after some of my own networking calls were made. Anywho, I just wanted to get this on your radar for now.

How to stub multiple response cookies?

First, thank you for this excellent library. I have a question. I don't see how to stub multiple response cookies. The OHHTTPStubsResponse class contains a dictionary for the stubbed response headers, and presumably to stub a single cookie, one would add an entry to this dictionary with the key "Set-Cookie". The problem is, an HTTP response containing several cookies will look like this on the wire:

Set-Cookie: abc=123; domain=.example.com; path=/
Set-Cookie: def=245; ...
Set-Cookie: ghi=356; ...

It's the same "Set-Cookie" header repeated for each cookie. Because NSDictionary does not allow duplicate keys, I don't see how to stub this sort of response.

Thank you,

-Paul

[Question] Is there a way to completely remove response time during unit tests?

I'm using OHHTTPStubs in my unit tests to capture the NSURLRequest so I can check that an API path and HTTP method are what they should be. I'm using Kiwi and the following is an example of what my test looks like.

beforeEach(^{
            [OHHTTPStubs addRequestHandler:^OHHTTPStubsResponse *(NSURLRequest *request, BOOL onlyCheck) {
                url = request.URL;
                method = request.HTTPMethod;
                return [OHHTTPStubsResponse responseWithFile:@"test.json" contentType:@"text/json" responseTime:0.1];
            }];
        });

        it(@"should fetch shows for user", ^{
            [MyClass myMethodWithResponse:^(id response) {
                                      // Calls GET http://someurl.com/i/am/checking
                                  }];

            NSString *testCase = [NSString stringWithFormat:@"http://someurl.com/i/am/checking];
            [[expectFutureValue(url) shouldEventually] equal:[NSURL URLWithString:testCase]];
            [[expectFutureValue(method) shouldEventually] equal:@"GET"];
        });

Is there a better way to achieve this? For these particularly tests, I'm not interested in returning a json object, but I just want to capture the request. I am sure I'm going about this the wrong way but not sure what the right direction is.

I should mention I'm aiming to speed up the test, as each request currently takes 0.204 seconds, and I have about 70 network related calls.

Request from NSURLSessionDataTask not passing stub's pass-everything pass block

Here's a fun one. I'm creating a stub to catch an upload request that I create using AFNetworking's -[NSURLSessionManager uploadTaskWithRequest:fromData:progress:completionHandler:] method. Here's my stub:

[OHHTTPStubs
 stubRequestsPassingTest:^BOOL(NSURLRequest *request)
 {
     return [request.URL.lastPathComponent isEqualToString:@"addSplash.php"];
 }
 withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
     NSDictionary *standardHeaders = @{ @"Content-Type":@"text/html"};
     return [OHHTTPStubsResponse responseWithData:nil statusCode:200 headers:standardHeaders];
 }];

Here's my test:

it(@"should set isUploading to YES", ^{
    client.isUploading = NO;
    [client sendNewSplashData:[NSData data] withLabel:@"SplashString" forLocation:[[CLLocation alloc] initWithLatitude:37 longitude:-80]];
    expect(client.isUploading).to.beTruthy();
});

And here's that -sendNewSplashData... method:

- (void)sendNewSplashData:(NSData *)splashData withLabel:(NSString *)label forLocation:(CLLocation *)location {

    self.isUploading = YES;

    long clientID = [[NSUserDefaults standardUserDefaults] integerForKey:@"clientID"];

    // Build request body
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSMutableData *body = [NSMutableData data];

    // Add body data
    // <EXCERPTED>

    // Build request with body
    NSURL *url = [self.baseURL URLByAppendingPathComponent:@"addSplash.php"];
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    [request addValue:contentType forHTTPHeaderField:@"Content-Type"];

    NSProgress *progress;
    NSURLSessionDataTask *task = [self uploadTaskWithRequest:request fromData:body progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        self.isUploading = NO;
    }];
    [task resume];
    [progress addObserver:self forKeyPath:@"fractionCompleted" options:NSKeyValueObservingOptionNew context:NULL];
}

When I run the test, an exception is thrown in -[OHHTTPStubs startLoading] at this assertion:

NSAssert(stub, @"At the time startLoading is called, canInitRequest should have assured that stub is != nil beforehand");

Back in the stub, if I simply return YES in the request test block so that all requests pass, this exception is still thrown. If I place a breakpoint in this block and look at request, I see that two requests hit the block--the one I expect, and a nil request. Strangely, when I place a breakpoint, run the test, hit the breakpoint, and continue in the debugger through each request, the test passes and no exception is thrown.

Can't find OHHTTPStubs.h when trying to run my tests on another Build Configuration.

Hello,

I want to build another build configuration in order to disable OHHTTPStubs with a debug build and hit my Staging server.

In order to do so I create another build configuration (duplicate of the Debug Build Configuration)

Duplicate Debug Build

Then I go to edit my scheme

Edit Scheme

And switch to my new Debug Copy configuration

Debug Duplicate

After that I hit Cmd+U to run my tests with the new Build Configuration

But I get a can't find headers error

headers

How could I make this work? Since I need to test my Debug build against staging or OHHTTPStubs depending on the build configuration.

PS: If I go back to the Debug Build Configuration, I don't get the error and everything is OK.

Deployment Target & AFNetworking 2.0

Hey there,

If you want to avoid compilation errors while using AFNetworking 2.0 the deployment target of OHHTTPStubs should be raised to iOS 7.0.

If you know of other workaround, let me know :)

Including OHHTTPStubs in project cause for rejection from AppStore

Hi, I included OHHTTPStubs in a project I submitted to the AppStore, but was subsequently rejected. The cause was "We found that your app uses one or more non-public APIs". After looking through the code, it turned out to be the bit in OHHTTPStubs.m, lines 168-175:

// Undocumented initializer obtained by class-dump
// Don't use this in production code destined for the App Store
@interface NSHTTPURLResponse(UndocumentedInitializer)
- (id)initWithURL:(NSURL*)URL
       statusCode:(NSInteger)statusCode
     headerFields:(NSDictionary*)headerFields
      requestTime:(double)requestTime;
@end

Maybe I missed it, but it would be very helpful to have this in the documentation (near the top? in the installation section?) highlighting this caveat.

OHHTTPStubsDescriptor <NSObject>

It'd be great if the OHHTTPStubsDescriptor protocol could also conform to the NSObject protocol. Right now, I have to do some kind of gross casting to quiet the compiler when I retain/release my OHHTTPStubsDescriptor object.

Stub not being called

I'm setting up a stub in an Specta spec that isn't getting called. Here's the code I'm using:

it(@"should request splashes", ^{
    __block BOOL success = NO ;

    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return [request.URL.host isEqualToString:@"zamba.cs.vt.edu"];
    }
                        withStubResponse: ^OHHTTPStubsResponse *(NSURLRequest *request) {
                            NSData *stubData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"findSplashesResponse" ofType:@"txt"]];
                            NSDictionary *standardHeaders = @{ @"Content-Type":@"text/html"};
                            return [OHHTTPStubsResponse responseWithData:stubData statusCode:200 headers:standardHeaders];
                        }].name = @"findSplashes.php";
    [OHHTTPStubs setEnabled:YES];

    [client POST:@"findSplashes.php"
      parameters:@{ @"hash": [client hashString],
                    @"lat":[NSString stringWithFormat:@"%f", vt.coordinate.latitude],
                    @"long":[NSString stringWithFormat:@"%f", vt.coordinate.longitude],
                    @"radius":@"1600" }
         success:^(NSURLSessionDataTask *task, id responseObject) {
             NSString *response = [[NSString alloc] initWithData:(NSData *) responseObject encoding:NSUTF8StringEncoding];
             success = [response isEqualToString:@"252\t5527.5387976613\t4\t4\t1387655919\t1387568319\t300\t40.739983\t-73.992951\n"] ? YES : NO;
         }
         failure:^(NSURLSessionDataTask *task, NSError *error) {
             success = NO;
         }];

    expect(success).will.beTruthy();
});

client is a singleton instance of an AFHTTPSessionManager from AFNetworking 2.0. Strangely, this test and other similar tests were passing originally--I don't know what I've done to break them! When the POST request is made, I can check that OHHTTPStubs.sharedInstance is the same as when the stub was created. I've added the +[OHHTTPStubs setEnabled:] call per other issues here. The block passed as thestubRequestsPassingTest:` parameter is never executed--all requests hit the network. Any ideas? Thanks!

Build failed when using OHHTTPStubs

  1. I've build the library in separate OHHTTPStubs project to get headers and .a file.
  2. In my project (My_Project) I right click and: "Add files to the project" where I add folder which contains headers and .a from OHHTTPStubs build folder and I make sure copy is checked.
  3. I import in MyNetworkMock class:
#import "OHHTTPStubs.h"
#import "OHHTTPStubsResponse.h"

Inside of this class I plan to add multiple of:

shouldStubRequestsPassingTest:withStubResponse:

I can not compile my project if I use OHHTTPStubs or OHHTTPStubsResponse

ERROR:

Screen Shot 2013-02-16 at 7 32 52 PM

Is there anything else I should have done?

Unable to disable OHHTTPStubs when using an AFHTTPSessionManager

I have an AFHTTPSessionManager subclass that I access through a shared singleton method. When I call setEnabled:NO OHHTPStubs still intercepts the network calls. I understand that AFHTTPSessionManager is using an NSURLSessionConfiguration so I have also tried passing this to the setEnabled:forSessionConfiguration: method but with no joy either.

Here is my shared singleton constructor:

@implementation WebServiceClient

+ (instancetype)sharedClient {
    static WebServiceClient *_sharedManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedManager = [[WebServiceClient alloc] initWithBaseURL:[NSURL URLWithString:WebAPIBaseURLString]];

        _sharedManager.requestSerializer = [AFJSONRequestSerializer serializer];
    });

    return _sharedManager;
}

@end

I am using OHHTPStubs in my unit tests (with Specta and Expecta) like this:

it(@"returns the user details upon successful login", ^AsyncBlock {

    webServiceClient = [WebServiceClient sharedClient];

    [OHHTTPStubs setEnabled:NO forSessionConfiguration:webServiceClient.session.configuration];

    [OHHTTPStubs stubRequestsPassingTest:requestTestBlock
                        withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
                            NSString* fixture = OHPathForFileInBundle(@"login_sucessful.json",nil);
                            return [OHHTTPStubsResponse responseWithFileAtPath:fixture
                                                                    statusCode:200 headers:@{@"Content-Type":@"text/json"}];
                        }];

    [webServiceClient loginUsername:correctUsername
                            password:correctPassword
                             success:^( NSString *authenticationToken) {
                                 done();
                             }
                             failure:nil];

});

I can't figure out why OHHTPStubs is still intercepting the network calls. Any help is very much appreciated.

Add some Unit Tests for this library

As suggested by @stanislaw in #8, adding some test coverage for various cases would be welcome.

Here are some ideas for those future unit tests:

Framework methods to test
  • Adding and removing requestHandlers
  • Adding simulated fixed delay to stubbed responses
  • Define simulated network bandwidth to stubbed responses
  • Building OHHTTPStubsResponse using some NSData
  • Building OHHTTPStubsResponse using a file
  • Building OHHTTPStubsResponse with custom response headers
  • Building OHHTTPStubsResponse with custom NSError
Request methods to test (at least)
  • Test case for sendAsynchronousRequest:queue:completionHandler:
  • Test case for sendSynchronousRequest:returningResponse:error:
  • Test case for connectionWithRequest:delegate: + NSURLConnectionDelegate implementation
  • Test case for -[NSString stringWithContentsOfURL:encoding:error:] and -[NSData dataWithContentsOfURL:]
  • Test cases when using AFNetworking
Threading contexts to test (at least)
  • When called from the main thread
  • When called from a secondary thread
  • Multiple, concurrent requests at the same time (including with response order different from request order)
Use cases to check (at least)
  • When the request succeed
  • When the request fails with server error (404 error, etc)
  • When the request times out

At the time startLoading is called, canInitRequest should have assured that stub is != nil beforehand

I'm using OHHTTPStubs on my unit tests (using XCTests) and sometimes my tests fail because of an assert in OHHTTPStubs.m (line 311).

I don't know if it's related, but I remove all stubs ([OHHTTPStubs removeAllStubs]) before each test is run (it's implemented on setUp method in a XCTestCase subclass that all my tests inherit from).

Here's the stacktrace:

2014-02-05 15:49:11.882 xctest[12918:220f] *** Assertion failure in -[OHHTTPStubsProtocol startLoading], /Users/usuario/marcelo.fabri/kiwi-sdk-ios/Pods/OHHTTPStubs/OHHTTPStubs/Sources/OHHTTPStubs.m:311
2014-02-05 15:49:11.884 xctest[12918:220f] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'At the time startLoading is called, canInitRequest should have assured that stub is != nil beforehand'
*** First throw call stack:
(
    0   CoreFoundation                      0x00b1d5e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x007958b6 objc_exception_throw + 44
    2   CoreFoundation                      0x00b1d448 +[NSException raise:format:arguments:] + 136
    3   Foundation                          0x00010fee -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 116
    4   KiwiSDKTests                        0x05f94f54 -[OHHTTPStubsProtocol startLoading] + 420
    5   Foundation                          0x00144932 __31-[_NSCFURLProtocolBridge start]_block_invoke + 59
    6   Foundation                          0x000ac945 -[NSBlockOperation main] + 88
    7   Foundation                          0x00105829 -[__NSOperationInternal _start:] + 671
    8   Foundation                          0x00082558 -[NSOperation start] + 83
    9   Foundation                          0x00143933 -[_NSCFURLProtocolBridgeWithTrampoline processEventQ] + 291
    10  Foundation                          0x00143fe2 -[_NSCFURLProtocolBridgeWithTrampoline pushEvent:from:] + 264
    11  Foundation                          0x001448f2 -[_NSCFURLProtocolBridge start] + 94
    12  Foundation                          0x00145b01 bridgeStart + 80
    13  CFNetwork                           0x00e4f9fb _ZN19URLProtocol_Classic28_protocolInterface_startLoadEPK20_CFCachedURLResponse + 65
    14  CFNetwork                           0x00e793e3 ___ZN19URLConnectionLoader27_private_ScheduleOriginLoadEPK13_CFURLRequestPK20_CFCachedURLResponse_block_invoke_2 + 147
    15  CFNetwork                           0x00e78026 ___ZNK19URLConnectionLoader25withExistingProtocolAsyncEU13block_pointerFvP11URLProtocolE_block_invoke + 30
    16  CFNetwork                           0x00eb90ef ___ZNK17CoreSchedulingSet13_performAsyncEPKcU13block_pointerFvvE_block_invoke + 25
    17  CoreFoundation                      0x00abed59 CFArrayApplyFunction + 57
    18  CFNetwork                           0x00dd85af _ZN19RunloopBlockContext7performEv + 139
    19  CFNetwork                           0x00eb96d2 _ZThn16_N19RunloopBlockContext24multiplexerClientPerformEv + 20
    20  CFNetwork                           0x00dd83dd _ZN17MultiplexerSource7performEv + 299
    21  CFNetwork                           0x00dd81f2 _ZN17MultiplexerSource8_performEPv + 76
    22  CoreFoundation                      0x00aa683f __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 15
    23  CoreFoundation                      0x00aa61cb __CFRunLoopDoSources0 + 235
    24  CoreFoundation                      0x00ac329e __CFRunLoopRun + 910
    25  CoreFoundation                      0x00ac2ac3 CFRunLoopRunSpecific + 467
    26  CoreFoundation                      0x00ac28db CFRunLoopRunInMode + 123
    27  Foundation                          0x0002c9de +[NSURLConnection(Loader) _resourceLoadLoop:] + 381
    28  Foundation                          0x00088597 -[NSThread main] + 76
    29  Foundation                          0x000884f6 __NSThread__main__ + 1275
    30  libsystem_pthread.dylib             0x0174e5fb _pthread_body + 144
    31  libsystem_pthread.dylib             0x0174e485 _pthread_struct_init + 0
    32  libsystem_pthread.dylib             0x01753cf2 thread_start + 34
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Any ideas?

Make a tag 1.0.1

Hey

Can you make a tag on master HEAD now ? I have a podspec file which I would like to point against original repo and not my Fork.

HTTP status code 300 will not be treated correctly by stubs

We have noticed that HTTP status code 300 is not handled correctly.

300 represents "multiple choices" and involves user interaction, so according to the specification it should be treated similar to a 2xx response to give the user the chance to respond.

NSURLConnection behaves correctly by responding with -connection:didReceiveResponse: while the stubs will treat it like a redirect which 300 is not.

NSURLConnection cookies

On iOS, NSURLConnection can (and does) save cookies sent in an HTTP response into storage automatically.

However, using OHHTTPStubs, this does not happen.

I'm setting the cookie with:

[OHHTTPStubs addRequestHandler:^OHHTTPStubsResponse *(NSURLRequest *request, BOOL onlyCheck) {
    return [OHHTTPStubsResponse responseWithData:[NSData dataWithBytes:[@"{}" UTF8String] length:2]
                                      statusCode:200
                                    responseTime:0
                                         headers:@{@"Set-Cookie" : @"JSESSIONID=42C1E2873DD8B2716EEE80DF69221A72"}];
}];

The NSURLConnection object is constructed simply with

[NSURLConnection connectionWithRequest:request delegate:self];

The NSURLConnectionDataDelegate methods are called similarly to what happens with a real connection, so I'm not sure what the cause is.

If there is an architectural reason (that is, the iOS APIs just don't allow OHHTTPStubs to do this), feel free to close this issue.

Thanks for the (otherwise 😄) great library!

User-Agent is missing from `NSURLRequest` in `stubRequestsPassingTest:...` when using `NSURLSessionConfiguraiton`?

I am setting up the userAgent string using NSURLSessionConfiguraiton:

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.HTTPAdditionalHeaders = @{ @"User-Agent": @"Test User Agent" };
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

The User-Agent is being sent over the network - I can see it using Charles Proxy. However, it is not coming though in the stub checker:

[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        NSDictionary* headers = request.allHTTPHeaders;
        // `headers` does not contain the user agent entry
    return YES;
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
    return nil;
}];

Setting JSON as response

Trying:

    id responseJSON = @{
        @"user" : @{ @"username" : @"test",
                                 @"firstname" : @"Test",
                                 @"lastname" : @"Test"}
    };

    [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
        return [request.URL.absoluteString isEqualToString:@"https://test.org/login"];
    } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:responseJSON];
        OHHTTPStubsResponse *response = [OHHTTPStubsResponse responseWithData:data statusCode:200 headers:@{@"Content-Type":@"application/json"}];
        return response;
    }];

I get my response back but its NIL.

I am using AFNetworking, specifically AFHTTPSessionManager.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.