I'm using OCMock 1.70 and am having a problem mocking a simple method that returns a BOOL value. Here's my code:
@interface MyClass : NSObject
- (void)methodWithArg:(id)arg;
- (BOOL)methodWithBOOLResult;
@end
@implementation MyClass
- (void)methodWithArg:(id)arg {
NSLog(@"methodWithArg: %@", arg);
}
- (BOOL)methodWithBOOLResult {
NSLog(@"methodWithBOOLResult");
return YES;
}
@end
- (void)testMock {
id real = [[[MyClass alloc] init] autorelease];
[real methodWithArg:@"foo"];
//=> SUCCESS: logs "methodWithArg: foo"
id mock = [OCMockObject mockForClass:[MyClass class]];
[[mock stub] methodWithArg:[OCMArg any]];
[mock methodWithArg:@"foo"];
//=> SUCCESS: "nothing" happens
NSAssert([real methodWithBOOLResult], nil);
//=> SUCCESS: logs "methodWithBOOLResult", YES returned
BOOL boolResult = YES;
[[[mock stub] andReturn:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
NSAssert([mock methodWithBOOLResult], nil);
//=> FAILURE: raises an NSInvalidArgumentException:
// Expected invocation with object return type.
}
What am I doing wrong?
You need to use andReturnValue:
not andReturn:
[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
Hint: andReturnValue:
accepts any NSValue
-- especially NSNumber
. To more quickly stub methods with primitive/scalar return values, skip the local variable declaration altogether and use [NSNumber numberWithXxx:...]
.
For example:
[[[mock stub] andReturnValue:[NSNumber numberWithBool:NO]] methodWithBOOLResult];
For auto-boxing bonus points, you can use the number-literal syntax (Clang docs):
[[[mock stub] andReturnValue:@(NO)] methodWithBOOLResult];
[[[mock stub] andReturnValue:@(123)] methodWithIntResult];
[[[mock stub] andReturnValue:@(123.456)] methodWithDoubleResult];
etc.
I'm using version 3.3.1 of OCMock and this syntax works for me:
SomeClass *myMockedObject = OCMClassMock([SomeClass class]);
OCMStub([myMockedObject someMethodWithSomeParam:someParam]).andReturn(YES);
See the OCMock Reference page for more examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With