使用OCMock看似不正确的模拟行为

时间:2015-04-08 03:53:43

标签: objective-c unit-testing objective-c-blocks ocmock

我在测试中做了类似的事情

- (void)testSomething {
    __block BOOL isActive = NO;
    void (^doSomething)(void) = ^void(void) {
        isActive = YES;
        .....
    }

    [[someMock stub] andDo:^(NSInvocation *invocation) {
        NSValue *returnValue = 
            [NSValue valueWithBytes:&isActive
                           objCType:@encode(BOOL)];
        [invocation setReturnValue:&returnValue];
     }] isSomeMockActive];

     [self.someObject doSomethingWithHandler:doSomething];

     /// === verify ===
}

// Assume isSomeMockActive is a function on some real object

// Function in the real object

- (void)doSomethingWithHandler:(void(^)void)handler {
    // ....
    if ([someMock isSomeMockActive]) {
        // ....
    }  
    handler();
    if ([someMock isSomeMockActive]) {
        // this still returns NO even though handler correctly
        // sets isActive to YES in the tests
    }
    // ....
}

我观察到的是,当isSomeMockActive被点击时isActive是正确的NO然后是YES,但isSomeMockActive返回的内容总是如此总是NO

PS:我尝试过使用[self.mock stub] andReturnValue:...],这似乎也有同样的问题。

我在做什么事吗?

1 个答案:

答案 0 :(得分:-1)

这似乎是某个地方的OCMock中的一个错误。虽然我不能确定错误的地方,但我还需要进一步调查一下。

更简单的解决方法是使用选择器来存根方法而不是块。因此,不要将isActive作为局部变量,而是将其设为iVar,然后就可以执行

 OCMStub([some mockIsSomeMockActive]).andCall(self, @selector(isActive))