2

我正在尝试使用 ocmock 学习单元测试。我发现很难从我正在单元测试的类中模拟另一个类的调用。

有人可以建议如何对 KeyChainUtils 类和 HttpRequest 类进行模拟调用:

使用 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;
 }
}
4

1 回答 1

2

从 OCMock 2.1 版开始,我们可以存根类方法。请参阅此链接以获取更多信息:http ://www.ocmock.org/features/

因此,我们可以像这样对类方法进行存根:

id keyChainUtilMock = [OCMockObject mockForClass:[KeyChainUtil class]];
[[[keyChainUtilMock stub] andReturn:@"aasdf"] loadValueForKey:USER_ID];

NSString* userId = [KeyChainUtil loadValueForKey:USER_ID];
NSLog(@" stubbed value-->%@", userId);

所以,在运行这段特定的代码之后。这里不调用实际的类方法,而是返回存根值。我希望这可以帮助你。

于 2014-08-20T10:49:31.730 回答