1

在测试类

-(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];
}

详细视图控制器

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

IN 主视图控制器

  -(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"

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

4

2 回答 2

3

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];
}

这应该有效。

于 2013-05-07T06:59:46.493 回答
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");
}
于 2013-05-07T07:03:31.463 回答