Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub a Method That Returns a BOOL with OCMock

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?

like image 921
rentzsch Avatar asked Dec 05 '10 02:12

rentzsch


3 Answers

You need to use andReturnValue: not andReturn:

[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
like image 125
Dave Dribin Avatar answered Sep 28 '22 04:09

Dave Dribin


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.
like image 31
EthanB Avatar answered Sep 28 '22 05:09

EthanB


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.

like image 33
Adil Hussain Avatar answered Sep 28 '22 04:09

Adil Hussain