Using OCMock to expect category methods yields "[NSProxy doesNotRecognizeSelector"...]"
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];
}开发者_如何学C
@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?
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
I ran into this error when a project library was being compiled with GCC option COPY_PHASE_STRIP
set to YES
so the symbols were not visible. The tests then ran against that library and could not see the methods that needed to be stubbed setting COPY_PHASE_STRIP=NO
fixed the issue
精彩评论