简体   繁体   English

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

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

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). 我试图在单元测试中测试超时处理程序(而不是主程序)。

The issue seems to be that the [NSRunLoop mainRunLoop] is not running in unit tests the way it does in the standard Run. 问题似乎是[NSRunLoop mainRunLoop]没有像标准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. 这是建议设置超时的方法。

However, in the Test run, this doesn't work. 但是,在测试运行中,这不起作用。 The timeoutHandler:(NSTimer*)timer routine is never called. 永远不会调用timeoutHandler:(NSTimer*)timer例程。

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? 有没有办法让我在运行和单元测试中都能使用超时?

When you use timers and the main runloop, you will need to manually run the runloop: 当您使用计时器和主runloop时,您将需要手动运行runloop:

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

where continueCondition could be some flag that indicates that the timeout handler was invoked and time_way_over_timeout a 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 ^^) 其中continueCondition可能是一些标志,表示已调用超时处理程序, time_way_over_timeout是当前时间与预先计算的最大执行时间的比较(因此您可以处理单元测试的“超时测试超时”^^)

Also see this blog post about asynchronous unit testing: http://dadabeatnik.wordpress.com/2013/09/12/xcode-and-asynchronous-unit-testing/ 另请参阅有关异步单元测试的博客文章: http//dadabeatnik.wordpress.com/2013/09/12/xcode-and-asynchronous-unit-testing/

Looks something like this in Swift 3.0 with XCTest. 在使用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