This is similar to Jon's response, couldn't fit it into a comment, though. The first step is to make sure you are not creating a real connection. The easiest way to achieve this is to pull the creation of the connection into a factory method and then substitute the factory method in your test. With OCMock's partial mock support this could look like this.
In your real class:
- (NSURLConnection *)newAsynchronousRequest:(NSURLRequest *)request
{
return [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
In your test:
id objectUnderTest = /* create your object */
id partialMock = [OCMockObject partialMockForObject:objectUnderTest];
NSURLConnection *dummyUrlConnection = [[NSURLConnection alloc]
initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"file:foo"]]
delegate:nil startImmediately:NO];
[[[partialMock stub] andReturn:dummyUrlConnection] newAsynchronousRequest:[OCMArg any]];
Now, when your object under test tries to create the URL connection it actually gets the dummy connection created in the test. The dummy connection doesn't have to be valid, because we're not starting it and it never gets used. If your code does use the connection you could return another mock, one that mocks NSURLConnection.
The second step is to invoke the method on your object that triggers the creation of the NSURLConnection:
[objectUnderTest doRequest];
Because the object under test is not using the real connection we can now call the delegate methods from the test. For the NSURLResponse we're using another mock, the response data is created from a string that's defined somewhere else in the test:
int statusCode = 200;
id responseMock = [OCMockObject mockForClass:[NSHTTPURLResponse class]];
[[[responseMock stub] andReturnValue:OCMOCK_VALUE(statusCode)] statusCode];
[objectUnderTest connection:dummyUrlConnection
answered 2012-03-29T09:07:15.893