0
votes

I am working on a custom networking library and writing some unit test cases for it. I am not sure how to go about it.

I have a RequestObject which is a subclass of NSOperation


@interface RequestOperation : NSOperation

@property (nonatomic, strong) NSURLRequest *URLRequest;
@property (nonatomic, strong, readonly) NSURLResponse *URLResponse;
@property (nonatomic, strong, readonly) NSError *connectionError;
@property (nonatomic, strong, readonly) NSData *responseData;

-(id)initWithURLRequest:(NSURLRequest*)request;

@end

In implementation I have a private category which has NSURLConnection.

I want to write a test case to check if URLResponse exist after the request is being sent


-(void)testIfResponseExist
{
    NSURL *url = [[NSURL alloc] initWithString:@"https://google.com"];
    NSURLRequest  *request = [[NSURLRequest alloc] initWithURL:url];

    myRequest = [[RequestOperation alloc] initWithURLRequest:request];
    [myRequest start];

    [self WaitFor:1];

    XCTAssertNotNil(myRequest.URLResponse, @"Response should not be nil");
}

Is this way of unit testing correct ?

Now this is sending the actual request to the server. However, I can also stub NSURLConnection and send dummy response. But I am not sure which way I should go. What are pros and cons of mock object ?

1

1 Answers

1
votes

Your test seems correct for testing the library, but I believe Mocking objects is more for application testing. You won't want to do mocking for your library test casts, but rather test cases in your app that are using your library.

I'll give you an example of the power of a mock object with unit testing.

I just helped write the automated framework on a heavily downloaded iOS app. We used OCMock and KiF to actually automate app content updates. In our automated test, we use the same exact code as the app does to do content updates. However, we OCMock the method that returns the content URL and have it return a different one. This is very similar to swizzling. Now the app will point to our testing URL to download content updates with when testing. With 1-2 lines of code, we have swapped out the URL without having to write any custom code.

id mock = [OCMockObject mockForClass:[MasterUpdater class]];
[[[mock stub] andReturn:[NSString stringWithFormat:@"URL",BASE_UPDATE_TEST_URL]] getMasterUpdateURL];

With this, MasterUpdater:getMasterUpdateURL was returning a custom URL. That's all we had to do in our unit test for us to switch the URL for our automated tests!

If we didn't use a mocking, then we would have written additional code/methods in our production code to handle our automated test.