Cocoa Stub返回带有OCMock的BOOL的方法
我使用的是OCMock 1.70,在模拟一个返回BOOL值的简单方法时遇到了一个问题。这是我的密码:Cocoa Stub返回带有OCMock的BOOL的方法,cocoa,unit-testing,ocmock,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
@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.
}
我做错了什么?您需要使用
和返回值:
而不是和返回值:
[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];
提示:
andReturnValue:
接受任何NSValue
——尤其是NSNumber
。要更快速地使用基元/标量返回值的存根方法,请完全跳过局部变量声明,并使用[NSNumber numberWithXxx:…]
例如:
[[[mock stub] andReturnValue:[NSNumber numberWithBool:NO]] methodWithBOOLResult];
对于自动装箱加分,可以使用数字文字语法():
我使用的是OCMock的3.3.1版,这种语法对我来说很有用:
SomeClass *myMockedObject = OCMClassMock([SomeClass class]);
OCMStub([myMockedObject someMethodWithSomeParam:someParam]).andReturn(YES);
有关更多示例,请参阅OCMock。较新版本的OCMock应允许OCMock_值也作用于常量
OCMOCK_值(NO)
、@NO
和@(NO)
都应该可以工作。
SomeClass *myMockedObject = OCMClassMock([SomeClass class]);
OCMStub([myMockedObject someMethodWithSomeParam:someParam]).andReturn(YES);