如何在为OCMock对象调用isKindOfClass时获取模拟值?

时间:2013-03-01 02:10:04

标签: objective-c unit-testing mocking ocmock

将OCMock对象传递给函数调用isKindOfClass的方法。但是对于单元测试,返回的值不是模拟类,而是OCMockObject

2 个答案:

答案 0 :(得分:1)

以下是整篇文章,解释了如何编写OCMock isKindOfClass方法(默认情况下不存在)以及如何使用它:http://blog.carbonfive.com/2009/02/17/custom-constraints-for-ocmock/

答案 1 :(得分:0)

如果要将OCMock对象传递给函数调用isKindOfClass的方法,则需要创建部分mock。以下代码可能对您有帮助。它对我有用。

-(void)testMyTest
{
    FirstViewController* masterVC = [[FirstViewController alloc]init];
    SecondViewController *second = [[SecondViewController alloc] init];
    id master = [OCMockObject partialMockForObject:second];
    [[master expect] getName:@"PARAM"];
    [masterVC doSomething:master];
    [master verify];

    [masterVC release];
    [second release];
}

FirstViewController中的doSomething方法

-(void)doSomething:(SecondViewController *)detail
{
    if ([detail isKindOfClass:[SecondViewController class]])
    {
        NSString * returnVal = [detail getName:@"PARAM"];
        NSLog(@"returnVal %@",returnVal);
    }
}

另一个替代方法是模拟isKindOfClass方法,因此测试用例将变为

- (void)testMyTest
{
     CalculatorViewController* masterVC = [[CalculatorViewController alloc]init];
     id master = [OCMockObject niceMockForClass:[SecondViewController class]];
     BOOL ret = YES;
     [[[master expect] andReturnValue:OCMOCK_VALUE(ret)] isKindOfClass:[SecondViewController class]];
     [[master expect] getName:@"PARAM"];
     [masterVC doSomething:master];
     [master verify];
}