Clearly we all write unit test to test our code, aren't we. ;)
Here is how I test my networking code.

To test networking code I use the open source framework [OHHTTPStubs](https://github.com/AliSoftware/OHHTTPStubs) by [AliSoftware](https://github.com/AliSoftware). I've added it to my project with [cocoapods](http://cocoapods.org). Search the web how to get cocoapods to work with a test target.

In Xcode go to `File > New > File...` and select `Objective-C test case class`. Name the class `DataFetcher`, click next and add it to the Test Target.

Import the header files `OHHTTPStubs.h` and `DataFetcher.h` into the test case class. We need a property of the class we would like to test. In the case of this example this is a `DataFetcher`. As we are testing asynchronous requests we also need a `BOOL` property to indicate if the API request is done.

[code language="objc"]
#import <XCTest/XCTest.h>
#import "OHHTTPStubs.h"
#import "DataFetcher.h"

@interface DataFetcherTests : XCTestCase
@property (nonatomic, strong) DataFetcher *dataFetcher;
@property (nonatomic, assign) BOOL done;
@end
[/code]

Now we edit the `setUp` and the `tearDown` methods to look like this:

[code language="objc"]
- (void)setUp {
[super setUp];
self.dataFetcher = [[DataFetcher alloc] init];
self.done = NO;
}

- (void)tearDown{
self.dataFetcher = nil;
[OHHTTPStubs removeAllStubs];
[super tearDown];
}
[/code]

We have to add a method which helps us to wait for the completion of the asynchronous requests.

[code language="objc"]
- (BOOL)waitForCompletion:(NSTimeInterval)timeoutSecs {
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutSecs];

do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
if([timeoutDate timeIntervalSinceNow] < 0.0)
break;
} while (!self.done);

return self.done;
}
[/code]
I've copied the code from the [Infinite Loop Blog](http://www.infinite-loop.dk/blog/2011/04/unittesting-asynchronous-network-access/).

Let's write the first test. This test simply tests if the expected API endpoint is called.

[code language="objc"]
- (void)testThatFetchGlobalStreamCallsAPI {
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
NSLog(@"request.URL.absoluteString: %@", request.URL.absoluteString);
BOOL adnAPICall = [request.URL.host isEqualToString:@"alpha-api.app.net"];
if (adnAPICall) {
XCTAssertEqualObjects(request.URL.absoluteString, @"https://alpha-api.app.net/stream/0/posts/stream/global");
}
return adnAPICall;
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
return nil;
}];

typeof(self) __weak weakSelf = self;
[self.dataFetcher fetchGlobalStreamWithCompletion:^(NSArray *globalPostArray, NSError *error) {
typeof(self) __strong strongSelf = weakSelf;
strongSelf.done = YES;
}];

XCTAssertTrue([self waitForCompletion:5.0f], @"Didn't complete in expected time.");
}
[/code]

Done! To check whether we really testing our code, change `fetchGlobalStreamWithCompletion:` to use another API endpoint and run the test (Cmd u). It should fail. Change the test back to the expected API endpoint and run the test again. Now the test should succeed.

Ok, our code calls the expected API endpoint. What about the response? Does our code proceed the response in a way we would expect? Let's add a test:
First we need a file with a response which looks like what we expect. Open the Terminal, navigate to the test folder of your project and put into the prompt:

[code]
echo '{"meta":{"min_id":"0","code":200,"max_id":"0","more":true},"data":[{"text":"This is a test response."}]}' > globalStreamResponse.json
[/code]

Add the file `globalStreamResponse.json` to the test target. The response from the real API is way more complicated. But we only want to test here whether the response is correctly put into the array and passed to the block. (Another test would be whether a more realistic API response is correctly transformed into objects.)

[code language="objc" highlight="10,12,19,24,25,27"]
- (void)testThatFetchGlobalStreamReturnsExpectedResponse {
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
NSLog(@"request.URL.absoluteString: %@", request.URL.absoluteString);
BOOL adnAPICall = [request.URL.host isEqualToString:@"alpha-api.app.net"];
if (adnAPICall) {
XCTAssertEqualObjects(request.URL.absoluteString, @"https://alpha-api.app.net/stream/0/posts/stream/global");
}
return adnAPICall;
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:@"globalStreamResponse" ofType:@"json"];
NSLog(@"path: %@", path);
return [OHHTTPStubsResponse responseWithFileAtPath:path statusCode:200 headers:@{@"Content-Type":@"text/json"}];
}];

typeof(self) __weak weakSelf = self;
[self.dataFetcher fetchGlobalWithCompletion:^(NSArray *globalPostArray, NSError *error) {
typeof(self) __strong strongSelf = weakSelf;

XCTAssertEqual([globalPostArray count], 1);

NSDictionary *expecedResponse = @{@"text" : @"This is an easy test response."};
id firstResponseElement = [globalPostArray firstObject];

XCTAssertTrue([firstResponseElement isKindOfClass:[NSDictionary class]]);
XCTAssertEqual([(NSDictionary*)firstResponseElement count], [expecedResponse count]);
for (NSString *keyStrings in expecedResponse) {
XCTAssertEqualObjects(expecedResponse[keyStrings], firstResponseElement[keyStrings]);
}
strongSelf.done = YES;
}];

XCTAssertTrue([self waitForCompletion:5.0f], @"Didn't complete in expected time.");
}
[/code]

In line 10 the file we created is loaded and this is used to create the response in line 12. The tests are in the lines 19, 24, 25 and 27.

In line 19 we are testing the number of the elements in the returned array.

In line 24 we test whether the first element in the array is of kind `NSDictionary`. This isn't really needed because if it wouldn't be an `NSDictionary` one of the later tests would fail. But the test doesn't hurt and it reminds us about what we are expecting.

The next test (line 25) tests the number of elements in the dictionary.

And finally we test all the elements in the dictionary (line 27). It's kind of worthless to have a loop here. But if we decide to change the test response to have more elements (for example we could use a real response from the App.net API) we would not have to change the test. Remove the loop if it bothers you.

This is how I test my networking code.

You can find the project on [github](https://github.com/dasdom/SimpleTableView). If you have any comments, feel free to contact me at App.net [@dasdom](https://alpha.app.net/dasdom) or at Twitter [@dasdom](https://twitter.com/dasdom).