views:

166

answers:

2

I want to unit test the custom init method of a class that inherits from NSURLConnection -- how would I do this if the init of my testable class invokes NSURLConnection's initWithRequest?

I'm using OCMock and normally, I can mock objects that are contained within my test class. For this inheritance scenario, what's the best approach to do this?

- (void)testInit
{   
    id urlRequest = [OCMockObject mockForClass:[NSURLRequest class]];

    MyURLConnectionWrapper *conn = [[MyURLConnectionWrapper alloc] 
                 initWithRequest:urlRequest delegate:self 
                 someData:extraneousData];
}

My class is implemented like this:

@interface MyURLConnectionWrapper : NSURLConnection {

}
- (id)initWithRequest:(NSURLRequest *)request 
             delegate:(id)delegate someData:(NSString *)fooData
@end

@implementation MyURLConnectionWrapper

- (id)initWithRequest:(NSURLRequest *)request 
             delegate:(id)delegate someData:(NSString *)fooData
{
    if (self = [super initWithRequest:request delegate:delegate]) 
    {
        // do some additional work here
    }

    return self;
}

Here's the error I get:

OCMockObject[NSURLRequest]: unexpected method invoked: _CFURLRequest

A: 

Your wrapper is calling the real thing: [super initWithRequest ...], and NSURLRequest is invoking some method _CFURLRequest for which you haven't set an expectation. Since you are making a wrapper, you are "stub"bing the NSURLConnection not "mock"ing it. And you probably don't want to engage the real object. You could make your wrapper implement any methods that your unit-under-test will call and do asserts inside them. Since you are not making a OCMockObject out of the NSURLConnection then you can't use the verify methods.

I'm still new at mocking in Objective-C so I don't yet have an approach for mocking the NSURLConnection.

Carrie Prebble
A: 

If you change mockForClass to niceMockForClass, you'll get a stub object that will silently ignore messages you don't care about, but you can still set expectations for the calls you do care about:

id urlRequest = [OCMockObject niceMockForClass:[NSURLRequest class]];
chrispix