objective-cocmockocmockito

Mock internal calls of a another class methods


I am trying to learn unit testing with ocmock. I am finding it difficult to mock calls of another class from a class which i am unit testing.

Can some one suggest how to make mock call to KeyChainUtils class and HttpRequest class:

Code to unit test with OCMock:

@implementation UserProfileService {
+(BOOL) isValidUser
{
    NSString* userId = [KeyChainUtil loadValueForKey:USER_ID]; //mock this call
    bool isValidUser = NO;
    if(userId && userId.length > 0){
        NSDictionary* response = [HTTPDataService getJSONForURL:@"http://xtest.com/checkuserid" forRequestData:@{@"userid": userId}];

        if(response && response[@"valid"]){
            isValidUser = [response[@"valid"] boolValue];             
        }else{
            NSLog(@"error in connecting to server. response => %@", response);
        }
    }
    return isValidUser;
 }
}

Solution

  • Starting with OCMock release 2.1, we can stub the class method. Please refer this link for more information: http://www.ocmock.org/features/

    So, we can stub the class method like this:

    id keyChainUtilMock = [OCMockObject mockForClass:[KeyChainUtil class]];
    [[[keyChainUtilMock stub] andReturn:@"aasdf"] loadValueForKey:USER_ID];
    
    NSString* userId = [KeyChainUtil loadValueForKey:USER_ID];
    NSLog(@" stubbed value-->%@", userId);
    

    So, after running this particular piece of code. The actual class method is not called here and the stubbed value is returned. I hope this helps you.