3

In the OCMock docs you can easily mock a class, OR a protocol:

id classMock = OCMStrictClassMock([SomeClass class]);
id protocolMock = OCMStrictProtocolMock(@protocol(SomeProtocol));

My question is: can you do both? Basically I want to mock out an MPMediaItem that also implements this protocol:

@protocol VBLoggableProtocol <NSObject>    
/*
 * Returns a string that gives a detailed description of the properites of this object
 */
- (NSString *)propertiesStr;
/*
 * Returns a string that simply identifies the object (ie song.title)
 */
- (NSString *)idStr;        
@end

But I have no idea how.. ideas?

abbood
  • 23,101
  • 16
  • 132
  • 246

3 Answers3

4

This is currently not possible with OCMock. There is an feature request for mocking multiple protocols (https://github.com/erikdoe/ocmock/issues/178). Maybe in a future version it'll be possible to "add" a protocol to an existing mock, but as of today this is not supported.

Erik Doernenburg
  • 2,933
  • 18
  • 21
1

It seems that OCMock doesn't currently support this.

The class I wanted to mock is MPMediaItem, so to work around this limitation.. I simply subclassed MPMediaItem and made that subclass implement that protocol:

@interface VBLoggableMediaItem : MPMediaItem <VBLoggableProtocol>

@end

@implementation VBLoggableMediaItem

# pragma mark - VBLoggableProtocol

..

- (NSString *)idStr
{
    return self.title;
}

@end

then I mocked that subclass:

-(VBLoggableMediaItem*) mockRandomMediaItem
{
    VBLoggableMediaItem* mock = OCMStrictClassMock([VBLoggableMediaItem class]);

    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"mock://%@", randomString(10)]];
    ...

    OCMStub([mock title]).andReturn(title);        
    OCMStub([mock idStr]).andReturn(title);

    return mock;
}
abbood
  • 23,101
  • 16
  • 132
  • 246
1

As Erik Doernenburg pointed out this is currently not possible with OCMock. As a workaround you can define a new Class as a Subclass you want to test implementing all the protocols you need.

@interface TestClass : SomeClass <SomeProtocol>
@end

@implementation TestClass
@end

In your Test Method you can use the TestClass as a Mock of SomeClass and SomeProtocol

id testClass = OCMClassMock([TestClass class]);
cornr
  • 653
  • 4
  • 20