Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C & OC Mock - Mocking a class method?

I need to be able to determine whether a class method was called or not. How can I do this with OCMock?

like image 273
aryaxt Avatar asked Dec 16 '22 15:12

aryaxt


2 Answers

Starting with OCMock release 2.1 this is supported out of the box. You can now stub class methods in the same way as you stub instance methods.

like image 73
Erik Doernenburg Avatar answered Jan 05 '23 21:01

Erik Doernenburg


One approach is to wrap the class method in a method on your own class. So let's say your class has to call [SomeOtherClass classMethod:someString]. You could create a method invokeClassMethod: on your class like this:

-(NSString *)invokeClassMethod:(NSString *)someString {
    return [SomeOtherClass classMethod:someString];
}

Then in your test, you create a partial mock and expect invokeClassMethod:

-(void)testSomething {
    id partialMock = [OCMockObject partialMockForObject:actual];
    [[[partialMock expect] andReturn:@"foo"] invokeClassMethod:@"bar"];

    [actual doSomething:@"bar"];

    [partialMock verify];
}

If you want to verify that invokeClassMethod isn't called, you can throw an exception:

-(void)testSomethingElse {
    id partialMock = [OCMockObject partialMockForObject:actual];
    [[[partialMock stub] andThrow:[NSException exceptionWithName:@"foo" reason:@"Should not have called invokeClassMethod:" userInfo:nil] invokeClassMethod:OCMOCK_ANY];

    [actual doSomething:@"bar"];
}

The excpetion will cause the test to fail if invokeClassMethod is called.

like image 37
Christopher Pickslay Avatar answered Jan 05 '23 21:01

Christopher Pickslay