OCMock测试失败 - 未调用预期的方法

时间:2013-05-07 06:22:27

标签: iphone ios objective-c unit-testing ocmock

IN测试类

-(void)testMyTest
{
MasterViewController* masterVC = [[MasterViewController alloc]init];//[OCMockObject mockForClass:[MasterViewController class]];
id master = [OCMockObject mockForClass:[DetailViewController class]];
 [[master expect] getStringVal:@"PARAM"];
[masterVC doSomething];
 [master verify];
}

IN detailViewController

-(NSString*)getStringVal:(NSString*)param
{
NSString *returnParam = [NSString stringWithFormat:@"%@-String",param];
return returnParam;
}

在主视图控制器中

  -(void)doSomething
 {
DetailViewController *detail = [[DetailViewController alloc]init];

[detail getStringVal:@"PARAM"];
NSString * returnVal = [detail getStringVal:@"PARAM2"];
NSLog(@"returnVal %@",returnVal);
NSLog(@"doSomething");
}

当我运行测试时,我收到以下错误:

  

doSomething的   Unknown.m:0:错误: - [iOS5ExampleTests testMyTest]:OCMockObject [DetailViewController]:未调用预期方法:getStringVal:@“PARAM”

看起来好像没有调用该方法。但是如果我在方法中设置断点,它会停止并告诉我该行已由应用程序执行,而且我也正确地获取了日志。

2 个答案:

答案 0 :(得分:2)

getStringVal方法在真实对象上被调用,因为你在doSomething方法中分配了新的DetailViewController实例,它不会被模拟对象调用。

相反,您可以在doSomething方法中进行一些修改

-(void)doSomething:(DetailViewController *)detail
{
     [detail getStringVal:@"PARAM"];
     NSString * returnVal = [detail getStringVal:@"PARAM2"];
     NSLog(@"returnVal %@",returnVal);
     NSLog(@"doSomething");
}

在你的测试用例中

-(void)testMyTest
{
    MasterViewController* masterVC = [[MasterViewController alloc]init];//[OCMockObject mockForClass:[MasterViewController class]];
    id master = [OCMockObject mockForClass:[DetailViewController class]];
    [[master expect] getStringVal:@"PARAM"];
    [[master expect] getStringVal:@"PARAM2"];
    [masterVC doSomething:master];
    [master verify];
}

这应该有用。

答案 1 :(得分:2)

Colud是因为您的Master模拟对象使用自己的详细信息视图控制器而不是模拟详细信息视图控制器?

-(void)testMyTest
{
MasterViewController* masterVC = [[MasterViewController alloc]init];//[OCMockObject mockForClass:[MasterViewController class]];
id detailVC = [OCMockObject mockForClass:[DetailViewController class]];

// This is the missing line. If you don't have such a property use setValue:forKey:
masterVC.detailViewController = detailVC

 [[master expect] getStringVal:@"PARAM"];
[masterVC doSomething];
 [master verify];
}


-(void)doSomething
{
    // This is the offending line: you should be using the mock object not a real one.
    DetailViewController *detail = [[DetailViewController alloc]init];
    [detail getStringVal:@"PARAM"];
    NSString * returnVal = [detail getStringVal:@"PARAM2"];
    NSLog(@"returnVal %@",returnVal);
    NSLog(@"doSomething");
}