cocoa - 使用 OCMock stub 返回 BOOL 的方法

标签 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.
}

我做错了什么?

最佳答案

您需要使用andReturnValue:而不是andReturn:

[[[mock stub] andReturnValue:OCMOCK_VALUE(boolResult)] methodWithBOOLResult];

关于cocoa - 使用 OCMock stub 返回 BOOL 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357106/

相关文章:

objective-c - 验证从另一个对象 OCMock 调用了一个方法

cocoa - 在 Mac OS X 桌面上绘图

objective-c - 绑定(bind)和有条件设置隐藏

java - 使用 RxJava 2 进行安卓测试

iOS OCMock 部分 vs 类模拟

iOS OCMock 带参数的回调方法

xcode - Nib 的 IBOutlet 未连接(nil)

objective-c - NSNumber 的格式化绝对值

unit-testing - 运行单元测试

unit-testing - Jest globalSetup 选项不起作用