views:

261

answers:

1

I'm using OCMock trying to test the behavior of NSURLConnection. Here's the incomplete test:

#include "GTMSenTestCase.h"
#import <OCMock/OCMock.h>

@interface HttpTest : GTMTestCase

- (void)testShouldConnect;

@end

@implementation HttpTest

- (void)testShouldConnect {
  id mock = [OCMockObject mockForClass:[NSURLConnection class]];

  NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
  NSURLRequest *request = [NSURLRequest requestWithURL:url];
  NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:mock startImmediately:NO];

  [[mock expect] connection:connection didReceiveResponse:OCMOCK_ANY];
}

@end

When mocking a class with category methods, which the delegate method connection:didReceiveresponse: is, I get the error:

Unknown.m:0:0 Unknown.m:0: error: -[HttpTest testShouldConnect] : *** -[NSProxy doesNotRecognizeSelector:connection:didReceiveResponse:] called!

Has anyone had a problem with this?

+1  A: 

Hi,

It looks like you have created a mock object of NSURLConnection. However, the NSProxy warning is correct, an NSURLConnection object does not have the selector connection:didReceiveResponse: - that's a selector that's passed to an object that implements the protocol .

You need to mock an object that implements NSURLConnectionDelegate. As the delegate protocol specifies connection:didReceiveResponse: you should not get an error :)

I have not had much experience with OCMock but this seems to remove the compile error :

@interface ConnectionDelegate : NSObject { }
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
@end

@implementation ConnectionDelegate
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { }
@end



@interface ConnectionTestCase : SenTestCase { }
@end

@implementation ConnectionTestCase

- (void)testShouldConnect {
 id mock = [OCMockObject mockForClass:[ConnectionDelegate class]];

 NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
 NSURLRequest *request = [NSURLRequest requestWithURL:url];
 NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:mock startImmediately:NO];

 [[mock expect] connection:connection didReceiveResponse:OCMOCK_ANY];
}

@end

Hope this helps,

Sam

deanWombourne