Stubbing the method "class" with OCMock

678 Views Asked by At

I'm new to OCMock, so I may have overlooked something simple, but my issue is that I can't seem to stub the method class on a mock I've created. Here's how I'm setting up part of my test:

//  Unit Test
id mock = [OCMockObject mockForClass:[MySubClass class]];
[[[mock stub] andReturn:[MySubClass class]] class];
...
[someObject someMethodWithParam:mock];
...

Here's my implementation of someMethodWithParam::

//  Implementation
- (void)someMethodWithParam:(MySuperClass *)param {
    [[param class] someClassMethod];
}

The problem is that [param class] returns OCClassMockObject instead of MySubClass. This results in an "unrecognized selector sent to class" error when someClassMethod is called. I've tried using a partial mock, but that didn't seem to help.

Edit:

Here's a simplified test that won't pass:

//  Unit Test
id mock = [OCMockObject mockForClass:[MySubClass class]];
[[[mock stub] andReturn:[MySubClass class]] class];
XCTAssertEqual([mock class], [MySubClass class], @"The mock's class should be MySubClass");
1

There are 1 best solutions below

1
On

Look at your -someMethodWithParam:. It not return anything. It's void. So this is wrong test for this method. You made mock which have to return something even if method can't return anything. This test should looks like following:

MyClass object = [MyClass new]; /// instance of class which has someMethodWithParam: method
id mock = [OCMockObject partialMockForObject:object];
[[mock expect] someClassMethod];

[mock someMethodWithParam:[OCMArg any]];
[mock verify];

In this method only what you can is test expectation. You can test if method in your method has been called. So you can test if when you call -someMethodWithParam method -someClassMethod has been called. That's all. And you have to create partial mock.