Reputation: 4235
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)
Upvotes: 7
Views: 6092
Reputation: 18922
I sometimes find it useful to test "private" methods / implementations -- perhaps don't call it a unit test if that breaks some kind of orthodoxy -- but for a complex implementation I may want to verify behavior on a more granular level than through the external interface.
In any event, I will expose class extension methods by creating a category in the test class:
@interface MyClass (ExposeForTest)
- (void)method;
@end
- (void)testMyClass
{
id mock = [OCMockObject mockForClass:MyClass.class];
[[mock expect] method];
[mock simpleMethod];
}
Upvotes: 4
Reputation: 7710
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];
}
Upvotes: 16