【问题标题】:IOS -NSRunLoop in XCTest: How Do I Get A Run Loop to Work in A Unit Test?XCTest 中的 IOS -NSRunLoop:如何让运行循环在单元测试中工作?
【发布时间】:2013-10-22 16:03:16
【问题描述】:

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

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

问题似乎是 [NSRunLoop mainRunLoop] 在单元测试中的运行方式不像在标准运行中那样运行。

我以这种方式超时:

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

这适用于标准运行。这是设置超时的推荐方式。

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

看起来好像有东西干扰了运行循环。

有什么方法可以让我在运行和单元测试中都使用超时?

【问题讨论】:

标签: ios unit-testing


【解决方案1】:

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

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

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

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

【讨论】:

  • 链接的 wordpress 博客文章现在受到保护,需要身份验证:(
【解决方案2】:

在带有 XCTest 的 Swift 3.0 中看起来像这样。

// 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
}

【讨论】:

  • 好主意,让我阅读了 XCTestExpectation 的文档,但不是调用者要求的,而是提供不同的服务(很容易实现自己的目的)。
  • 同意:我应该删除它还是离开它?
  • 不要删除
猜你喜欢
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-13
  • 2013-09-26
相关资源
最近更新 更多