开发者

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 "methodWithB开发者_StackOverflowOOLResult", 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜