0

我正在使用 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
4

1 回答 1

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];
}

这个测试对我来说通过了。

于 2013-08-30T17:18:49.617 回答