本文介绍了在单元测试中,使用dispatch_asyc执行队列中传递的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我 dispatch_async 队列中的阻止如下:

If I dispatch_async a block on main queue like this:

-(void) myTask {
  dispatch_async(dispatch_get_main_queue(), ^{
      [self.service fetchData];
   });
}

在单元测试中,我可以通过手动运行执行主队列中传递的块像这样的主循环:

In unit test, I can execute the block passed in main queue by manually run the main loop like this:

-(void)testMyTask{
  // call function under test
  [myObj myTask];
  // run the main loop manually!
  [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01]];
  // now I can verify the function 'fetchData' in block is called
  ...
}

现在,我有另一个类似的函数,它将块发送到 主队列以外的顺序队列:

Now, I have another similar function which dispatch block to an sequential queue other than main queue:

-(void) myTask2 {
  dispatch_async(dispatch_queue_create("my.sequential.queue", NULL), ^{
      [self.service fetchData];
   });
}

在单元测试中,我现在如何手动执行块?

In unit test, how can I execute the block manually now?

-(void)testMyTask2{
  // call function under test
  [myObj myTask2];
  // How to manually execute the block now?
}

=== Clarify ===

我想手动执行的原因是因为我不喜欢任何Wait-For-Timeout方式进行测试。因为等待时间取决于CPU速度,所以在不同的机器上可能会有所不同。我想手动执行传递给队列的块(与我对主队列测试用例的操作方式相同),然后验证结果。

The reason why I want to manually execute is because I don't like any Wait-For-Timeout way doing the test. Because waiting time is depending on CPU speed, on different machines could be different. I'd like to manually execute the block passed to queue (the same way as how I did for the main queue test case) and then verify the result.

推荐答案

您可以在测试函数中创建队列。

You could create the queue in your test function.

-(void) myTask2:(dispatch_queue_t*)queue {
    dispatch_async(*queue, ^{
        [self.service fetchData];
    });
}

-(void)testMyTask2{
    dispatch_queue_t queue = dispatch_queue_create("my.sequential.queue", NULL);
    [myObj myTask2:&queue];

    dispatch_sync(queue, ^{
    });
}

(刚刚实现 currentRunLoop 不需要)

这篇关于在单元测试中,使用dispatch_asyc执行队列中传递的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 21:03