It's always hard to test methods that call class methods, such as NSURLConnection sendSynchronousRequest
Here are a few options:
a) Use Matt Gallagher invokeSupersequent macro to intercept the call. Your unit test will contain this code:
@implementation NSURLConneciton (UnitTests) + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error { if (someFlagYourTestUsesToInterceptTheCall) { // return test NSData instance } return invokeSupersequent(request, &response, &error); } @end
Then you set someFlagYourTestUsesToInterceptTheCall to make it intercept the call and return the test data.
b) Another alternative is to port this call to your own method in the test class:
-(NSData *)retrieveNewsCount:(NSURLRequest *)request { NSHTTPURLResponse *response; NSError *error; return [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; }
Then intercept this call in a test case using OCMock:
-(void)testNewsCount {
In this case, OCMock stub:andCall:onObject:someMethod intercepts this call only to your object in order to insert some test data during testing.
source share