How to unit test api calls using AFNetworking - ios

I have an iOS app I'm working on, which connects to a third-party web service. I have around 50 different calls, and want to write unit tests using Kiwi, but I have no idea where to start.
As I'm not responsible for the API, I need to just check that my calls are pointing to the correct URL, using the correct GET or POST method.
Is there any way to test this properly?
Heres an example of one of my calls:
+ (void)listsForUser:(NSString *)username
response:(void (^)(NSArray *lists))completion
{
NSString *path = [NSString stringWithFormat:#"user/list.json/%#/%#", TRAKT_API_KEY, username];
[TNTraktAPIManager requestWithMethod:GET
path:path
parameters:nil
callback:^(id response) {
completion(response);
}];
}
Which calls the following helper method
+ (void)requestWithMethod:(HTTPMethod)method
path:(NSString *)path
parameters:(NSDictionary *)params
callback:(void (^)(id response))completion
{
NSString *methodString = #"POST";
if (method == GET) {
methodString = #"GET";
}
// Setup request
NSURLRequest *request = [[TraktAPIClient sharedClient] requestWithMethod:methodString
path:path
parameters:params];
// Setup operation
AFJSONRequestOperation *operation =
[AFJSONRequestOperation JSONRequestOperationWithRequest:request
success:^(NSURLRequest *request,
NSHTTPURLResponse *response,
id JSON) {
id jsonResults = JSON;
completion(jsonResults);
} failure:^(NSURLRequest *request,
NSHTTPURLResponse *response,
NSError *error,
id JSON) {
id jsonResults = JSON;
completion(jsonResults);
NSLog(#"%s: error: %#", __PRETTY_FUNCTION__, error);
}];
// TODO: Queue operations
[operation start];
}

If you set a shouldEventually expectation on the helper class and use the receive:(SEL)withArguments:(id)... form, then you can check that the argument received is what you'd expect it to be.
Two gotchas worth knowing about are setting the expectation before making the call; and using the shouldEventually form rather than should so that the test is delayed long enough for the call to be made.

I highly recommend checking out OHHTTPStubs for unit testing your API Classes.
Unit tests should be deterministic and adding internet a potentially unpredictable API into the mix makes the testing conditions non-deterministic.
OHTTPStubs will allow you to stub the response to your outgoing HTTP Requests. Basically, it intercepts your HTTP Traffic and if the request matches criteria that you set, it gives a canned response that you declare in JSON (rather than an unpredictable result from the API). This allows you to configure different response scenarios in your test classes: ie. 404 error, partial response data, etc.. to use in your tests.
Here's an example:
I created this JSON Stub and saved as a JSON file:
{
"devices" : [
{
"alarm" : {
"alarm_id" : 1,
"attack_time" : "<null>",
"defined_time" : "2014-04-14T04:21:36.000Z",
"device_id" : 7,
"is_protected" : 0
},
"device_type" : "iPhone",
"id" : 7,
"os_version" : "7.1"
}
],
"email" : "mystubemail#gmail.com",
"facebook_id" : 5551212,
"id" : 3,
"name" : "Daffy Duck"
}
Whenever I network requests are made in the API Call, this JSON is returned because of this OHHTTPStub which is declared in the test class to run before all tests.
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
BOOL stringFound;
if ([[request.URL description] rangeOfString:[NSString stringWithFormat:#"%#devices/register?", BASEURL]].location != NSNotFound)
{
stringFound = YES;
}
NSLog(#"%d", stringFound);
return stringFound;
} withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) {
// Stub it with our "RegisterDevice.json" stub file
return [[OHHTTPStubsResponse responseWithFileAtPath:OHPathForFileInBundle(#"RegisterDevice.json",bundle)
statusCode:200 headers:#{#"Content-Type":#"text/json"}] requestTime:1.0 responseTime:1.0];
}];
I'm not sure if Kiwi allows for async testing, but if not I also recommend looking into Specta and the matching framework Expecta. They allow for super easy Asynchronous unit testing, which when combined with OHHTTPStubs provides all you need to unit test API Calls.

Related

Async method testing using XCTest

I am new to XCTest and started writing test cases. I have written couple of functional test cases, but I got stuck in below async method call. I read XCTestExpectation class reference but not able to mock properly.
It will be really helpful If get to know how to test below method.
Here are the details of method that I want to test,
- (void)getStudentInfo:(void (^)(BOOL))success failure:(void (^)(NSError *error))failure {
// Request formation CODE
// Here I have post call to AFNetworking
[httpSessionManager POST:uri
parameters:para
success:^(NSURLSessionDataTask *task, id responseObject) {
failure:^(NSURLSessionDataTask *task, NSError *error) {
}]
}
You need to look into XCTest expectations which provide support for async testing. Here is a simplified example (in Swift, but the same applies for Objective-C)
func testAsync() {
let expectation = expectationWithDescription("Waiting for something")
let someObject = ...
someObject.doSomethingWithCompletion({ () in
expectation.fulfill()
})
waitForExpectationsWithTimeout(3.0, handler: nil)
// Verify Results
}
The simple explanation is that the test will wait at the waitFor... until the fulfil() method is called. Or timeout and throw an error.
You can also set expectations on notifications and properties. Check the XCTest class doco for details.

How to mock CoralCall [call:error:] method to return error

We generate Obj-C code from CoralClient, and here is a method from CoralCall class:
- (id)call:(CoralModel *)request error:(NSError * __autoreleasing *)error;
And here is basically my code to use CoralCall:
Request *request = ...;
// Make the Coral call
NSError *error = nil;
int count = 0;
do {
// There's no result, because this API won't return anything
[coralCall call:request error:&error];
++count;
} while (error != nil && count < MAX_RETRY_COUNT);
completionHandler(error);
How can I use OCMock to mock the coralCall object to return an error in the [call:error:] method? I want to unit test the retry logic, and there seem to be no way to achieve this.
Note: I can easily mock the success of the call, but not failure, like this:
// Doesn't matter what the returned value is, so use nil for simplicity
OCMStub([self.coralCall call:[OCMArg any] error:(NSError * __autoreleasing *)[OCMArg anyPointer]]).andReturn(nil);
UPDATED: this is now resolved with Erik's answer. In case anyone need an answer, here is how to mock the error:
NSError *error = OCMClassMock([NSError class]);
OCMStub([self.coralCall call:[OCMArg any] error:[OCMArg setTo:error]]).andReturn(nil);
It looks like what you want to do is described in the reference documentation in section 2.5 (Returning values in pass-by-reference arguments): http://ocmock.org/reference/#stubing-methods

How one tests http requests in iOS 8?

In ruby I used to test http requests with vcr gem which recorded the request so the tests didn't send request to real host. Is there anything like this in iOS8 world?
The requests I want to test really need to be recorded since those requests may be outdated in some time and will return some other response
P.S. It would be great if it was some default Apple/iOS approach/library like XCTest for testing in general
What you want is something like OHHTTPStubs or Nocilla or AMY server. All of them essentially use NSURLProtocol to intercept your request and allow you to designate a response. We used OHHTTPStubs but pick the one with the feature set closest to your use case.
Here's an example of an OHHTTPStubs implementation in a unit test for a service that talks to a single REST endpoint:
NSString *loadRoomJSON = #{ #"key" : #"value" }; /* some JSON */
NSNumber identifier = #1;
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
NSString *url = [NSString stringWithFormat:#"v1/user/%#/room", identifier];
XCTAssert([request.URL.relativePath containsString:url], #"Expected certain URL");
return YES;
} andRespond:^OHHTTPStubsResponse *(NSURLRequest *request) {
return [OHHTTPStubsResponse responseWithJSONObject:loadRoomJSON statusCode:200 headers:nil];
}];
XCTestExpectation *loadPromise = [self expectation:#"Room loaded"];
[service loadRoomOnSucceed:^(Room *room) {
// Do your asserts here. For us, the JSON is mapped to an object
// so for example you could assert that the object is mapped correctly
[loadPromise fulfill];
} onFail:^(NSError *error) {
expect(error).to.beNil();
}];
[self waitForExpectationsWithTimeout:1.0 handler:^(NSError *error) {
expect(error).to.beNil();
}];
In reality our tests are shorter since we write wrapper/helpers to make it read better so this is an exploded-out version. Should give you the general idea. OHHTTPStubs (if you use it) has helper functions to load responses directly from files as well.
Im not sure if I understood you correct. But if I understand you right, you should be able to use XCTest to test your request and response.
class Tests:XCTestCase{
func testing(){
var expectation = self.expectationWithDescription("Your request")
var url = NSURL(string: "http://yourUrl.com")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
if let httpRes = response as? NSHTTPURLResponse {
println("status code=",httpRes.statusCode)
//200 means OK
if httpRes.statusCode == 200 {
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
}else{
println("error \(error)")
}
}
}
}

How to update JSON File from web server

I have my local data in json file like :
{
"locations": [
{
"title": "The Pump Room",
"place": "Bath",
"latitude": 51.38131,
"longitude": -2.35959,
"information": "The Pump Room Restaurant in Bath is one of the city’s most elegant places to enjoy stylish, Modern-British cuisine.",
"telephone": "+44 (0)1225 444477",
"visited" : true
},
{
"title": "The Eye",
"place": "London",
"latitude": 51.502866,
"longitude": -0.119483,
"information": "At 135m, the London Eye is the world’s largest cantilevered observation wheel. It was designed by Marks Barfield Architects and launched in 2000.",
"telephone": "+44 (0)8717 813000",
"visited" : false
},
{
"title": "Chalice Well",
"place": "Glastonbury",
"latitude": 51.143669,
"longitude": -2.706782,
"information": "Chalice Well is one of Britain's most ancient wells, nestling in the Vale of Avalon between the famous Glastonbury Tor and Chalice Hill.",
"telephone": "+44 (0)1458 831154",
"visited" : true
}
]
}
I want to update the json file which is there on the webserver whenever the refresh button touched?
The overall idea is to refresh the local data from server and use it without internet connectivity
Please Help...
The most appropriate solution depends on your exact requirements. For example:
Do you need authentication?
Do you require to load the JSON in background mode?
Is your JSON huge, so that loading it into memory wouldn't be that nice to the system?
Do you need to cancel a running request, since there are chances that it stalls or takes too long?
Do you need to load many requests at once in parallel?
and a few more.
If you can answer all requirements with No, then the most simple approach will suffice:
You can use NSURLConnection's convenient class method in the asynchronous version
+ (void)sendAsynchronousRequest:(NSURLRequest *)request queue:(NSOperationQueue *)queue completionHandler:(void (^)(NSURLResponse*, NSData*, NSError*))handler
You can find more info here:
Using NSURL Connection
Furthermore Cocoa and Cocoa Touch provides more advances techniques in NSURLConnection and NSURLSession to accomplish this task. You can read more in the official documentation URL Loading System Programming Guide.
Here a short sample how you can use the asynchronous convenience class method: sendAsynchronousRequest:queue:completionHandler::
// Create and setup the request
NSMutableURLRequest* urlRequest = [NSURLRequest requestWithURL:url];
[urlRequest setValue: #"application/json; charset=utf-8" forHTTPHeaderField:#"Accept"];
// let the handler execute on the background, create a NSOperation queue:
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse* response,
NSData* data,
NSError* error)
{
if (data) {
// check status code, and optionally MIME type
if ( [(NSHTTPURLResponse*)(response) statusCode] == 200 /* OK */) {
NSError* error;
// here, you might want to save the JSON to a file, e.g.:
// Notice: our JSON is in UTF-8, since we explicitly requested this
// in the request header:
if (![data writeToFile:path_to_file options:0 error:&error]) {
[self handleError:err]; // execute on main thread!
return;
}
// then, process the JSON to get a JSON object:
id jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:&error];
... // additionally steps may follow
if (jsonObject) {
// now execute subsequent steps on the main queue:
dispatch_async(dispatch_get_main_queue(), ^{
self.places = jsonObject;
});
}
else {
[self handleError:err]; // execute on main thread!
}
}
else {
// status code indicates error, or didn't receive type of data requested
NSError* err = [NSError errorWithDomain:...];
[self handleError:err]; // execute on main thread!
}
}
else {
// request failed - error contains info about the failure
[self handleError:error]; // execute on main thread!
}
}];
See also: [NSData] writeToURL:options:error
Edit:
handleError: SHALL be implemented as follows:
- (void) handlerError:(NSError*)error
{
dispatch_async(dispatch_get_main_queue(), ^{
[self doHandleError:error];
});
}
This ensures, when you display a UIAlertView for example, that your UIKit methods will be executed on the main thread.

How to run unit tests on code that has failing assertions in Xcode?

In Xcode i am running tests on creating users based on ID. When a wrong ID is set the test should fail. Though this test fails since the method it tests has assertions in itself:
[[Apiclient sharedClient] findAndCreateUserWithID:nil success:^(Player *player) {
STFail(#"should not be able to create player with no ID");
} failure:^(NSError *error) {
}];
the method called:
- (void)findAndCreateUserWithID:(NSNumber *)ID success:(void (^)(Player *))createdPlayer failure:(void (^)(NSError *error))failure
{
NSParameterAssert(ID);
Will fail the test when parameter ID is nil. I know this is a pretty stupid example since it will always fail, but there are more assertions allready in code that are more useful. Whats the best practice on running Xcode unit tests which test code that allready has assertions?
As of late 2014, if you're using the new testing framework XCTest, you'll want to use XCTAssertThrowsSpecificNamed instead of the older STAssertThrowsSpecificNamed method:
void (^expressionBlock)() = ^{
// do whatever you want here where you'd expect an NSParameterAssertion to be thrown.
};
XCTAssertThrowsSpecificNamed(expressionBlock(), NSException, NSInternalInconsistencyException);
NSParameterAssert throws an NSInternalInconsistencyException (source) when its assertion fails. You can test that this happens with the STAssertThrowsSpecificNamed macro. For example:
void (^expressionBlock)() = ^{
[[Apiclient sharedClient] findAndCreateUserWithID:nil success:^(Player *player) {
} failure:^(NSError *error) {
}];
};
STAssertThrowsSpecificNamed(expressionBlock(), NSException, NSInternalInconsistencyException, nil);
I use an expression block there to make it easier to put that much code in the macro.

Resources