How to start with OCMock and check if method was invoked

ios, objective-c, ocmock, tdd, unit-testing

Solution

You never actually create an object of the class that you want to test. Also, you have to `expect` first, then invoke the 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];
}

Problem

I'm trying to deal with `OCMock`. I created simple class `MyClass`. ``` @interface MyClass : NSObject - (NSString *)simpleMethod; @end @implementation MyClass - (NSString *)simpleMethod { [self method]; return @"simple"; } - (void)method { NSLog(@"ABC"); } @end ``` What I want to check is if method `method` was invoked when `simpleMethod` has been called. Now I've got following code but it doesn't work: ``` - (void)testMethodInvoked { id mock = [OCMockObject mockForClass:[MyClass class]]; [[mock stub] simpleMethod]; SEL selector = NSSelectorFromString(@"method"); [[mock expect] methodForSelector:selector]; [mock verify]; } ``` How should I test this case? I think that is pretty easy to do, but I have no idea how solve this problem. How to create mock and call method `simpleMethod` which invoke method `method`? Current log: ``` <unknown>:0: error: -[OCMockTestTests testOne] : OCMockObject[MyClass]: expected method was not invoked: methodForSelector:@selector(method) ```

Original source