如何使用OCMock模拟NSObject的类方法

时间:2017-08-08 22:48:45

标签: objective-c unit-testing nsobject ocmock

有没有办法创建NSObject的实例?我正在尝试从NSObject模拟一个类方法,并收到objc[86140]: no class for metaclass 0x1065c0e38的错误。

- (void)testChainMethodCalled
{
  id controller = [OCMockObject partialMockForObject:[MyController class]];
  MyController *controller = controllerId;

  id object = [[OCMockObject partialMockForObject:[NSObject alloc] init] ];
  [[[object expect] classMethod] cancelPreviousPerformRequestsWithTarget:self selector:@selector(chainMethod) object:nil];

  [controller callTestMethod];
  OCMVerifyAll(object);
}

1 个答案:

答案 0 :(得分:0)

在模拟类方法时,您应该使用OCMClassMock。您正在使用partialMockForObject来模仿对象实例,而不是类本身。

对于你的例子:

id objectMock = OCMClassMock([NSObject class]);

然后你可以像这样模拟类上的任何方法:

OCMStub(ClassMethod([objectMock classMethod])).andReturn(mockValue)

其中classMethod是你嘲笑的类方法,而mockValue是你为该类方法嘲笑的虚假值

有关此

的更多详情,请参阅http://ocmock.org/reference/#mocking-class-methods