iOS中的-NSRunLoop在XCTest中:如何获得一个运行循环在unit testing中工作?

好。 我环顾四周,没有find我的问题的确切答案。

我试图在unit testing(而不是主要运行)中testing超时处理程序。

这个问题似乎是[NSRunLoop mainRunLoop]没有在标准的运行中在unit testing中运行。

我以这种方式做超时:

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

这在标准运行中起作用。 这是设置超时的推荐方式。

但是,在testing运行中,这不起作用。 timeoutHandler:(NSTimer*)timer例程永远不会被调用。

看起来似乎有什么东西干扰了运行循环。

有没有办法让我的超时工作在运行和unit testing?

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

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

其中continueCondition可以是一些标志,指示超时处理程序被调用, time_way_over_timeout是当前时间与预先计算的最大执行时间的比较(所以你可以为你的unit testing处理“超时testing”)^^)

另请参阅有关asynchronousunit testing的此博客文章: http : //dadabeatnik.wordpress.com/2013/09/12/xcode-and-asynchronous-unit-testing/

在Swift 3.0中用XCTest看起来像这样。

 // somebody has to call the .fulfill() method on this variable // to the expectation will fail after 25 seconds var asyncExpectation : XCTestExpectation! func testExample() { asyncExpectation = expectation(description: "longRunningFunction") self.waitForExpectations(timeout: 25.0) { (error) in if let error = error { print("Error \(error)") } } // more stuff here }