XOSest中的IOS -NSRunLoop:如何在单元测试中运行循环? [英] IOS -NSRunLoop in XCTest: How Do I Get A Run Loop to Work in A Unit Test?

查看:131
本文介绍了XOSest中的IOS -NSRunLoop:如何在单元测试中运行循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

行。我环顾四周,并没有找到问题的确切答案。

OK. I looked around, and didn't find an exact answer to my issue.

我正在尝试在单元测试中测试超时处理程序(而不是主程序)。

I am trying to test a timeout handler in a unit test (not the main run).

问题似乎是 [NSRunLoop mainRunLoop] 没有像单元测试一样运行标准运行。

The issue seems to be that the [NSRunLoop mainRunLoop] is not running in unit tests the way it does in the standard Run.

我以这种方式执行超时:

I do my timeouts in this manner:

NSTimer *pTimeoutHandler = [NSTimer 
    timerWithTimeInterval:2.0 
    target:self 
    selector:@selector(timeoutHandler:) 
    userInfo:nil 
    repeats:NO
];
[[NSRunLoop mainRunLoop] addTimer:pTimeoutHandler forMode:NSRunLoopCommonModes];

这适用于标准运行。这是建议设置超时的方法。

This works in the standard run. This is the recommended manner of setting a timeout.

但是,在测试运行中,这不起作用。永远不会调用 timeoutHandler:(NSTimer *)计时器例程。

However, in the Test run, this doesn't work. The timeoutHandler:(NSTimer*)timer routine is never called.

好像有什么东西在干扰运行循环。

It appears as if something is interfering with the run loop.

有没有办法让我在运行和单元测试中都能使用超时?

Is there any way for me to get the timeout to work in both run and unit test?

推荐答案

当你使用计时器和主runloop时,你需要手动运行runloop:

When you use timers and the main runloop, you will need to manually run the runloop:

while (continueCondition || !time_way_over_timeout)  {
    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

其中 continueCondition 可以是一些标志,表示已调用超时处理程序, time_way_over_timeout 当前时间与预先计算的最大执行时间的比较(因此您可以处理超时的超时测试为你的单元测试^^)

where continueConditioncould be some flag that indicates that the timeout handler was invoked and time_way_over_timeouta comparision of the current time with a pre-calulated maximum execution time (so you can handle a "timeout of timout test" for your unit test ^^)

另见这篇关于异步单元测试的博文: http://dadabeatnik.wordpress.com/2013/09/12/xcode-and-asynchronous-unit-testing/

Also see this blog post about asynchronous unit testing: http://dadabeatnik.wordpress.com/2013/09/12/xcode-and-asynchronous-unit-testing/

这篇关于XOSest中的IOS -NSRunLoop:如何在单元测试中运行循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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