3

我正在尝试与 OCMock 一起编写 XCTest (iOS7, XCode5)。

我有一个实现 CLLocationManagerDelegate 协议的类,并且有一个属性是 CLLocationManager 的一个实例。(我将 CLLocationManager 的实例提供给我的初始化方法,以便我可以在运行时或测试时注入它)。

在测试委托类时,我创建了一个模拟 CLLocationManager。

在测试中,我想实现这样的目标:

[[[[mockLocationManager stub] classMethod] andReturnValue:kCLAuthorizationStatusDenied] authorizationStatus];
result = [delegateUnderTest doMethod];
//Do asserts on result etc etc

问题是,XCode 抱怨我的代码。

test.m:79:68: Implicit conversion of 'int' to 'NSValue *' is disallowed with ARC
test.m:79:68: Incompatible integer to pointer conversion sending 'int' to parameter of type 'NSValue *'

kCLAuthorizationStatusDenied 是我理解的一个 int(在 TypeDef 中定义)。所以,我不能用

[[[[mockLocationManager stub] classMethod] andReturn:kCLAuthorizationStatusDenied] authorizationStatus];

这会期望一个对象('andReturn' 是一个 'id')。

有任何想法吗?

4

1 回答 1

2

您需要将值装箱到NSValue实例中,而不是传递原始值本身。例如:

[[[mockLocationManager stub] andReturnValue:@(kCLAuthorizationStatusDenied)] authorizationStatus];

上面使用了NSNumbers 的 Objective-C 文字语法。另外,我省略了classMethod上面的调用CLLocationManager没有实例方法authorizationStatus

可以在OCMock 网站上找到对此的更多支持:

如果方法返回原始类型,则 andReturnValue: 必须与值参数一起使用。不能直接传递原始类型。

这也是编译器错误告诉你的 - 你传递的是一个int而不是一个NSValue实例。

于 2013-09-28T07:42:13.077 回答