I ended up solving this problem using another library, OHHTTPStubs
. One can easily return mock objects through AFNetworking
, stub out certain requests & vary response/ request times.
It is well documented here. Also here is the github page. A stub is removed like this:
[OHHTTPStubs removeStub:stub];
Here is some sample code:
// A mockJSON file is loaded here
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"sampleJSON18.json"];
NSData* data = [NSData dataWithContentsOfFile:filePath];
NSError* error = nil;
id mockJSON = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
//*** stub out AFNetworkingRequestOperation and return custom NSDictionary "mockJSON", in order to see how it is handled
id<OHHTTPStubsDescriptor> stub = nil;
stub = [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return [[request.URL path]isEqualToString:@"/v1/epg/packages/59/broadcasts"]; // this means that any request which is equal to the above string is stubbed, return YES to stub *all* requests
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
// The `stubbing` procedure occurs in this block.
return [[OHHTTPStubsResponse responseWithJSONObject:mockJSON statusCode:200 headers:nil] requestTime:1.0f responseTime:5.0f]; // one can vary the request/responseTime here
}];
stub.name = @"getChannelsWithBroadcastsForDay";
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
// The response object is now the mockJSON object, i.e. the original request is stubbed out
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// handle failure
}
}];
[self enqueueHTTPRequestOperation:operation];
return operation;
}