【问题标题】:Issue stubbing a method问题存根方法
【发布时间】: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


    【解决方案1】:

    我无法重现 - 这是你在做什么?

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

    我通过了这个测试。

    【讨论】:

    • 差不多,除了在这个过程中还有一个额外的管理器对象。我已经用更深入的代码示例更新了这个问题。
    • 啊,经过一些更仔细的调试后,似乎我在使用共享模拟外设的原始完成之前以某种方式运行了第二个类似的测试。使外围设备成为本地对象后,测试通过。我会接受你的回答,因为它现在在技术上对我有用。
    猜你喜欢
    • 2021-04-10
    • 2011-07-26
    • 2014-09-19
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多