我正在尝试与OCMock打交道.我创建了简单的类MyClass.
@interface MyClass : NSObject - (NSString *)simpleMethod; @end @implementation MyClass - (NSString *)simpleMethod { [self method]; return @"simple"; } - (void)method { NSLog(@"ABC"); } @end
我想要检查的是调用simpleMethod时是否调用了method方法.现在我有以下代码,但它不起作用:
- (void)testMethodInvoked { id mock = [OCMockObject mockForClass:[MyClass class]]; [[mock stub] simpleMethod]; SEL selector = NSSelectorFromString(@"method"); [[mock expect] methodForSelector:selector]; [mock verify]; }
我该如何测试这个案例?我认为这很容易做到,但我不知道如何解决这个问题.
如何创建调用方法方法的mock和调用方法simpleMethod?
当前日志:
<unknown>:0: error: -[OCMockTestTests testOne] : OCMockObject[MyClass]: expected method was not invoked: methodForSelector:@selector(method)
解决方法
您实际上从未创建要测试的类的对象.此外,您必须首先,然后调用方法:
- (void)testMethodInvoked { // first create an object that you want to test: MyClass *object = [[MyClass alloc] init]; // create a partial mock for that object id mock = [OCMockObject partialMockForObject:object]; // tell the mock object what you expect [[mock expect] method]; // call the actual method on the mock object [mock simpleMethod]; // and finally verify [mock verify]; }