我正在使用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.
}
我做错了什么?
答案 0 :(得分:63)
您需要使用andReturnValue:
而不是andReturn:
[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
答案 1 :(得分:5)
提示:andReturnValue:
接受任何 NSValue
- 尤其是NSNumber
。要使用原始/标量返回值更快地存根方法,请完全跳过局部变量声明并使用[NSNumber numberWithXxx:...]
。
例如:
[[[mock stub] andReturnValue:[NSNumber numberWithBool:NO]] methodWithBOOLResult];
对于自动拳击奖励积分,您可以使用数字 - 文字语法(Clang docs):
[[[mock stub] andReturnValue:@(NO)] methodWithBOOLResult];
[[[mock stub] andReturnValue:@(123)] methodWithIntResult];
[[[mock stub] andReturnValue:@(123.456)] methodWithDoubleResult];
etc.
答案 2 :(得分:1)
我正在使用OCMock的3.3.1版本,这种语法对我有用:
SomeClass *myMockedObject = OCMClassMock([SomeClass class]);
OCMStub([myMockedObject someMethodWithSomeParam:someParam]).andReturn(YES);
有关更多示例,请参阅OCMock documentation。