使用OCMock存储返回BOOL的方法

ren*_*sch 29 cocoa unit-testing ocmock

我正在使用OCMock 1.70,并且在模拟返回BOOL值的简单方法时出现问题.这是我的代码:

@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.
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Dav*_*bin 63

您需要使用andReturnValue:andReturn:

[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
Run Code Online (Sandbox Code Playgroud)


Eth*_*anB 5

提示:andReturnValue:接受任何 NSValue - 特别是NSNumber.要使用原始/标量返回值更快地存根方法,请完全跳过局部变量声明并使用[NSNumber numberWithXxx:...].

例如:

[[[mock stub] andReturnValue:[NSNumber numberWithBool:NO]] methodWithBOOLResult];
Run Code Online (Sandbox Code Playgroud)

对于自动拳击奖励积分,您可以使用数字 - 文字语法(Clang docs):

[[[mock stub] andReturnValue:@(NO)] methodWithBOOLResult];
[[[mock stub] andReturnValue:@(123)] methodWithIntResult];
[[[mock stub] andReturnValue:@(123.456)] methodWithDoubleResult];
etc.
Run Code Online (Sandbox Code Playgroud)