【问题标题】:Use OCMock to mock a block expectation使用 OCMock 模拟块期望
【发布时间】:2012-10-11 11:08:35
【问题描述】:

我是 OCMock 的新手,我打算模拟一个请求调用。需要模拟的 API 按如下定义执行。

   [ProductRequest requestProductUpdateUrl: @"testUrl" withParameters:params   error:^(NSString *updateUrl, NSError *error){
        if (!error && [updateUrl length] !=0 ) {
           NSLog(@"Success");
        } else {
             NSLog(@"Error");
        }
   }];

知道如何使用 OCMock 模拟方法 requestProductUpdateUrl 吗?

【问题讨论】:

  • 看起来requestProductUpdateUrl 是一个类方法。那是对的吗?你不能用 OCMock 模拟类方法。
  • @Christopher 是的,这是一个类方法,但我也可以将其修改为不是类方法。谢谢你指出。如果是这样,我的代码将被修改 self.productService = [OCMockObject mockForClass:[ProductService class]]; [self.productService requestProductUpdateUrl: @"testUrl" withParameters:params error:^(NSString *updateUrl, NSError *error){ if (!error && [updateUrl length] !=0 ) { NSLog(@"Success"); } else { NSLog(@"错误"); } }];
  • 好的,那么你想测试什么?您是否只想验证它是否已被调用,是否已使用某个块调用,等等?
  • 我想为方法提供一个模拟存根

标签: objective-c ios ocmock


【解决方案1】:

这个功能还没有实现,虽然我认为他们正在努力。我也必须这样做:

semaphore = dispatch_semaphore_create(0);
[myObject myFunctionWithCallback:^(BOOL success){
     if(success)
        dispatch_semaphore_signal(semaphore);
     else
        STFail(@"Call failed"); dispatch_semaphore_signal(semaphore);

}];
[self waitForSemaphore];

使用等待功能是这样的:

- (void)waitForSemaphore;
{
float step_duration = .1;
float wait_steps = 2 / step_duration;
while (dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC / 10)) && wait_steps > 0){
    CFRunLoopRunInMode(kCFRunLoopDefaultMode,step_duration, YES);
    wait_steps--;
}

if (wait_steps <= 0) {
    STFail(@"Timeout!");
}

}

【讨论】:

    猜你喜欢
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多