我正在使用CoreBluetooth,所以在我的单元测试中,我正在嘲笑所有CB对象,所以他们返回我想要的东西。在我的一个测试中,我模拟了一个CBPeripheral,并像这样存根委托方法:
[[[mockPeripheral stub] andReturn:device] delegate];
传入的设备是我的包装对象,它保留在外围设备上。在测试的后期,我在设备上调用了一个方法,然后检查:
NSAssert(_peripheral.delegate == self, @"Empty device");
此行在测试期间被声明,因为 _peripheral.delegate!= self 。
我已经调试过了,并确保 _peripheral 是一个OCMockObject。当断言检查 _peripheral 的委托时,为什么短脚方法不会返回设备?
这是详细的代码:
@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
答案 0 :(得分:0)
我无法重现这一点 - 这就是你正在做的事情吗?
@interface Bar : NSObject <CBPeripheralDelegate>
@property (nonatomic, strong) CBPeripheral *peripheral;
- (void)peripheralTest;
@end
- (void)peripheralTest
{
NSAssert(_peripheral.delegate == self, @"Empty device");
}
// In test class:
- (void)testPeripheral
{
Bar *bar = [Bar new];
id peripheralMock = [OCMockObject mockForClass:CBPeripheral.class];
[[[peripheralMock stub] andReturn:bar] delegate];
bar.peripheral = peripheralMock;
[bar peripheralTest];
}
这个测试通过我。