Objective-c – iphone OCMockObject and unit-testing a class that inherits from NSURLConnection

iphoneobjective cocmock

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

Best Answer

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]];
Related Topic