Search code examples
iphoneobjective-cios5ocmock

How to stub "respondsToSelector" method


I'm trying to do something like this:

id synchronizerDelegate = [OCMockObject mockForProtocol:@protocol(SynchronizerDelegate)];
BOOL isRespondsToSelector = NO;
[[[synchronizerDelegate stub] andReturnValue:OCMOCK_VALUE(isRespondsToSelector)] respondsToSelector:@selector(didLoadFullImage:)];
GHAssertFalse([synchronizerDelegate respondsToSelector:@selector(didLoadFullImage:)], nil);

Here is the definition of SynchronizerDelegate

@protocol SynchronizerDelegate <NSObject>
- (void)didLoadFullImage:(NSData *)data;
@end

But this test case always fail (the returned value is YES).

Anyone tried to stub "respondsToSelector" method before?


Solution

  • When you mockForProtocol, the mock doesn't actually conform to the protocol, so OCProtocolMockObject overrides respondsToSelector to return YES for methods defined in the protocol.

    OCMock depends on forwardInvocation:, which is invoked by the runtime when an object hasn't defined the method being called. Since OCProtocolMockObject implements respondsToSelector, you can't mock it.

    If you describe what you're trying to achieve, there might be another way to approach it.