Grand Central Dispatch和单元测试 [英] Grand Central Dispatch and unit testing

查看:94
本文介绍了Grand Central Dispatch和单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的测试用例跟随Apple的文档,我没有看到我期待的结果。

I have written a simple test case that follows Apple's documentation and I am not seeing the results that I'm expecting.

以下是代码:

- (void)testExample2
{
    NSLog(@"1");

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); 

    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"3");
             dispatch_semaphore_signal(semaphore);
        });

    NSLog(@"2");
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);

    NSLog(@"4");    
    dispatch_release(semaphore);    
}

我希望看到:1,2,3,4但是我的控制台只显示我1,3。

I would expect to read: 1, 2, 3, 4 but instead my console just shows me 1, 3.

我已经能够使用 DISPATCH_TIME_NOW 解决这个问题了while循环和NSLoop hack但上面的代码应该有点工作......对吗?

I've been able to work around the issue using DISPATCH_TIME_NOW in a while loop together with a NSLoop hack but the code above should kind of work... right?

干杯......

UPDATE

我刚才意识到我应该使用一个单独的队列而不是 dispatch_main_queue()

I just realised that I should be using a separate queue rather than dispatch_main_queue()

推荐答案

在我的 tearDown

while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW)) {
    NSLog(@"...Tearing Down Tests..");
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                             beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
}
dispatch_release(semaphore);  

并将信号量创建推送到 setUp

and pushing the semaphore creation into the setUp.

这篇关于Grand Central Dispatch和单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆