yasuoza diary

web and life

Stub sharedManager with OCMock

If you are iOS/Mac developer, you may have written singleton like following convention:

1
2
3
4
5
6
7
8
9
static UserModelManager *sharedManager_ = nil;

+ (UserModelManager *)sharedManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedManager_ = [[UserModelManager alloc] init];
    });
    return sharedManager_;
}

If UserModelManager has secretKey instance method like:

1
2
3
4
- (NSString *)secretKey
{
    return "secret key provided from server side";
}

Then you can call secretkey method via

1
[[UserModelManager sharedManager] secretkey];

It’s OK until you have to stub secretKey in a test.

The solution to stub sharedManager and secretkey is:

1
2
3
_mockUserModelManager = [OCMockObject niceMockForClass:[UserModelManager class]];
[[[_mockUserModelManager stub] andReturn:@"test-key"] secretkey];
[[[[_mockUserModelManager stub] classMethod] andReturn:_mockUserModelManager] sharedManager];

To clean up your stub methods, DO NOT forget stopMocking in tearDown.

1
2
3
4
5
6
- (void)tearDown
{
  [super tearDown];

  [_mockUserModelManager stopMocking];
}

Comments