存根函数在我的测试用例中不起作用

时间:2016-05-30 13:53:39

标签: ios objective-c unit-testing ocmock

我正在使用OCMock 3在iOS项目中编写我的联合测试。

我在foo类下有一个School方法:

@implementation School
-(NSString *)foo:
{
    // I need to mock this MyService instance in my test
    MyService *service = [[MyService alloc] init];

    // I need to stub the function return for [service getStudent]
    Student *student = [service getStudent];
    if (student.age == 12) {
       //log the age is 12
    } else {
      //log the age is not 12
    }
    ...
}

Student看起来像这样:

@interface Student : NSObject
@property NSInteger age;
...
@end

在我的测试用例中,我希望将方法调用[service getStudent]存根,以返回Student实例,其中age值为12我定义:

// use mocked service
id mockService = OCMClassMock([MyService class]);
OCMStub([[mockService alloc] init]).andReturn(mockService);

// create a student instance (with age=12) which I want to return by function '-(Student*) getStudent:'
Student *myStudent = [[Student alloc] init];
myStudent.age = 12;

// stub function to return 'myStudent'
OCMStub([mockService getStudent]).andReturn(myStudent);

// execute foo method
id schoolToTest = [OCMockObject partialMockForObject:[[School alloc] init]];
[schoolToTest foo];

但是,当我运行测试用例时,student方法返回的-(Student*)getStudent:不是12岁,为什么?

=====更新====

我在互联网上注意到,有人建议将allocinit分隔为存根。我也试过了,但它并没有像它说的那样工作:

// use mocked service
id mockService = OCMClassMock([MyService class]);
OCMStub([mockService alloc]).andReturn(mockService);
OCMStub([mockService init]).andReturn(mockService);
// stub function to return 'myStudent'
OCMStub([mockService getStudent]).andReturn(myStudent);

当我这样做时&运行我的测试用例,-(Student*)getStudent:方法的真实实现被调用...我无法理解为什么人们说它有效。

1 个答案:

答案 0 :(得分:0)

您无法模拟init方法。这在文档(Section 9.3)中说明,但也许它太隐藏了。