【发布时间】:2013-08-30 15:59:05
【问题描述】:
我正在使用 CoreBluetooth,因此在我的单元测试中,我正在模拟所有 CB 对象,以便它们返回我想要的。在我的一个测试中,我模拟了一个 CBPeripheral,并像这样存根委托方法:
[[[mockPeripheral stub] andReturn:device] delegate];
传入的设备是我的包装对象,它保留在外围设备上。稍后在测试中,我在 device 上调用一个方法,然后检查:
NSAssert(_peripheral.delegate == self, @"Empty device");
由于_peripheral.delegate != self,此行在测试期间被断言。
我已经调试过了,并确保 _peripheral 是一个 OCMockObject。当断言检查 _peripheral 的委托时,为什么存根方法不返回 device?
详细代码如下:
@interface Manager : NSObject
- (void)connectToDevice:(Device*)device;
@end
@implementation Foo
- (void)connectToDevice:(Device*)device {
if([device checkDevice]) {
/** Do Stuff */
}
}
@end
@interface Device : NSObject {
CBPeripheral _peripheral;
}
- (id)initWithPeripheral:(CBPeripheral*)peripheral;
@end
@implementation Device
- (id)initWithPeripheral:(CBPeripheral*)peripheral {
self = [super init];
if(self) {
_peripheral = peripheral;
_peripheral.delegate = self;
}
return self;
}
- (BOOL)checkDevice {
NSAssert(_peripheral.delegate == self, @"Empty device");
return YES;
}
@end
@implementation Test
__block id peripheralMock;
beforeAll(^{
peripheralMock = [OCMockObject mockForClass:[CBPeripheral class]];
});
//TEST METHOD
it(@"should connect", ^{
Device *device = [[Device alloc] initWithPeripheral:peripheralMock];
[[[peripheralMock stub] andReturn:device] delegate];
[manager connectToDevice:device];
}
@end
【问题讨论】:
标签: ios objective-c unit-testing ocmock