本文介绍了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];
}

在detailViewController中

IN detailViewController

-(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");
}

运行测试时,出现以下错误:

When I run the tests I get the following error:

好像没有调用该方法.但是,如果我为该方法设置一个断点,它将停止并显示该行已由应用程序执行,并且我也可以正确获取日志.

It looks as if the method was not called. But if I set a breakpoint the the method, it stops and shows me that the line was executed by the application and I am also getting the logs properly.

推荐答案

getStringVal方法在真实对象上被调用,因为您已在doSomething方法内分配了DetailViewController的新实例,因此未在模拟对象上调用它.

getStringVal method gets invoked on the real object, as you have allocated new instance of DetailViewController inside doSomething method, it is not getting called on mocked object.

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

Instead you can do some modification in the doSomething method

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

这应该有效.

这篇关于OCMock测试失败-未调用预期方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:30