繁体   English   中英

XOSest中的IOS -NSRunLoop:如何在单元测试中运行循环?

[英]IOS -NSRunLoop in XCTest: How Do I Get A Run Loop to Work in A Unit Test?

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

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

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

我以这种方式做我的超时:

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

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

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

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

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

当您使用计时器和主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/

在使用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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM