Stubbing Methods不适用于OCMock3.4

时间:2017-07-03 02:29:11

标签: ios objective-c unit-testing ocmock

Stubbing Methods可以很好地使用'NSUserDefaults',但它似乎不适用于我的自定义方法。

我的测试代码如下:

- (void)testExample 
{
    id userDefaultMock = OCMClassMock([NSUserDefaults class]);
    OCMStub([userDefaultMock standardUserDefaults]).andReturn(userDefaultMock);
    OCMStub([userDefaultMock objectForKey:[OCMArg any]]).andReturn(@"user defaults mock obj");


    id managerMock = OCMClassMock([ViewManager class]);
    OCMStub([managerMock sharedInstance]).andReturn(managerMock);
    OCMStub([managerMock generateObjWithObj:[OCMArg any]]).andReturn(@(11));

    ViewController *vc = [[ViewController alloc]init];
    [vc publicMethod];

}
ViewController中的

代码:

- (void)publicMethod
{
    [[NSUserDefaults standardUserDefaults]setObject:@"mockObj" forKey:@"mockObjKey"];
    id obj = [[NSUserDefaults standardUserDefaults]objectForKey:@"mockObjKey"];
    NSLog(@"mockObjKey:%@",obj);

    NSNumber *num = @(0);
    NSNumber *i = [[ViewManager sharedInstance] generateIndexWithNumber:num];
    NSLog(@"i expected to be 1, actual :%ld",i.integerValue);
}
ViewManager中的

代码:

static ViewManager *sharedViewManager = nil;

+ (id)sharedInstance
{
    if (nil == sharedViewManager)
    {
        sharedViewManager = [[ViewManager alloc]init];
    }
    return sharedViewManager;
}
- (NSNumber *)generateIndexWithNumber:(NSNumber *)index
{
    NSLog(@"generateIndexWithNumber:%ld",index.integerValue);
    return @(index.integerValue + 1);
}

和控制台输出如下:

2017-07-03 10:12:25.812 OC_Unit[2214:64454] mockObjKey:user defaults mock obj
2017-07-03 10:12:25.812 OC_Unit[2214:64454] generateIndexWithNumber:0
2017-07-03 10:12:25.812 OC_Unit[2214:64454] i expected to be 1, actual :1

如果shubbing方法有效,最后一行输出应该是'我希望是1,实际:11'。我想知道,为什么它没有按预期输出。

1 个答案:

答案 0 :(得分:1)

看起来你正在追踪generateObjWithObj:,但代码正在调用generateIndexWithNumber: