使用 OCMock 存根返回 BOOL 的方法
我正在使用 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.
}
我做错了什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用
andReturnValue:
而不是andReturn:
You need to use
andReturnValue:
notandReturn:
提示:
andReturnValue:
接受任何NSValue
——尤其是NSNumber
。要更快地使用基元/标量返回值的存根方法,请完全跳过局部变量声明并使用[NSNumber numberWithXxx:...]
。例如:
对于自动装箱奖励积分,您可以使用数字-文字语法(Clang 文档):
Hint:
andReturnValue:
accepts anyNSValue
-- especiallyNSNumber
. To more quickly stub methods with primitive/scalar return values, skip the local variable declaration altogether and use[NSNumber numberWithXxx:...]
.For example:
For auto-boxing bonus points, you can use the number-literal syntax (Clang docs):
我使用的是 OCMock 3.3.1 版本,此语法适用于我:
请参阅 OCMock 参考 页面了解更多例子。
I'm using version 3.3.1 of OCMock and this syntax works for me:
See the OCMock Reference page for more examples.