我正在使用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岁,为什么?
=====更新====
我在互联网上注意到,有人建议将alloc
和init
分隔为存根。我也试过了,但它并没有像它说的那样工作:
// 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:
方法的真实实现被调用...我无法理解为什么人们说它有效。