Search code examples
objective-cocmock

OCMock - Mocking class method?


I'm trying to mock a class method, and it doesn't seem to be working as expected. any thoughts?

@implementation ApplicationVersionManager

+ (NSString *)appVersion {
   return [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

@end

Test

- (void)testSomething {
   OCMStub([ApplicationVersionManager appVersion]).andReturn(@"3.0");
   NSString *version = [ApplicationVersionManager appVersion];
   // version is nil. Why?
}

Solution

  • While OCMock can stub methods on existing objects, you still need a mock object to set up the stubs. The following should work:

    - (void)testSomething {
       id mock = OCMClassMock([ApplicationVersionManager class]);
       OCMStub([mock appVersion]).andReturn(@"3.0");
       NSString *version = [ApplicationVersionManager appVersion];
    }