存根初始化]不工作,但接受的答案说,它应该工作

我的testingfunction非常简单:

@implementation MyHandler ... -(void) processData { DataService *service = [[DataService alloc] init]; NSDictionary *data = [service getData]; [self handleData:data]; } @end 

我使用OCMock 3来进行unit testing。

我需要存根 [[DataService alloc] init]返回一个模拟实例 ,我试图从这个问题 (这是一个接受的答案)的答案存根[[SomeClazz alloc] init]

 // Stub 'alloc init' to return mocked DataService instance, // exactly the same way as the accepted answer told id DataServiceMock = OCMClassMock([DataService class]); OCMStub([DataServiceMock alloc]).andReturn(DataServiceMock); OCMStub([DataServiceMock init]).andReturn(DataServiceMock); // run function under test [MyHandlerPartialMock processData]; // verify [service getData] is invoked OCMVerify([dataServiceMock getData]); 

我在testing函数中设置了断点,运行unit testing时确定调用了[service getData] ,但是我上面的testing代码(OCMVerify)失败了。 为什么?

是否因为被testing的函数没有使用我的模拟 DataService ? 但在这个问题上接受的答案告诉它应该工作。 我现在感到困惑…

我想知道如何stub [[SomeClazz alloc] init]返回模拟实例与OCMock?

你不能模拟init因为它是由模拟对象本身实现的。 mocking init在你连接的答案中工作的原因是因为它是一个自定义的init方法 。 如果您不想使用dependency injection,则必须为DataService编写一个可以模拟的自定义init方法。

在你的实现中添加一个自定义的init方法:

 // DataService.m ... - (id) initForTest { self = [super init]; if (self) { // custom initialization here if necessary, otherwise leave blank } return self; } ... 

然后更新MyHandler实现来调用这个initForTest

 @implementation MyHandler ... -(void) processData { DataService *service = [[DataService alloc] initForTest]; NSDictionary *data = [service getData]; [self handleData:data]; } @end 

最后更新你的testing存根initForTest

 id DataServiceMock = OCMClassMock([DataService class]); OCMStub([DataServiceMock alloc]).andReturn(DataServiceMock); OCMStub([DataServiceMock initForTest]).andReturn(DataServiceMock); // run function under test [MyHandlerPartialMock processData]; // verify [service getData] is invoked OCMVerify([dataServiceMock getData]); 

可以随意重命名initForTest只要它不被称为init