Jul*_*ien 2 unit-testing uiwindow ios swift uialertcontroller
我一直在使用以下帖子作为如何显示UIAlertController与特定无关的from代码的指导UIViewController。现在,我要对该代码进行单元测试:
func showAlert(alert: UIAlertController, animated: Bool, completion: (()->Void)?) 
{
    let alertWindow = UIWindow(frame: UIScreen.mainScreen().bounds)
    // Keep a strong refence to the window. 
    // We manually set this to nil when the alert is dismissed
    self.alertWindow = alertWindow
    alertWindow.rootViewController = UIViewController()        
    if let currentTopWindow = UIApplication.sharedApplication().windows.last {
        alertWindow.windowLevel = currentTopWindow.windowLevel + 1
    }
    else {
        // This case only happens during unit testing
        Logger.trace(ICELogLevel.Error, category: .Utility, message: "The application doesn't have a window being displayed!")
    }
    // preload the viewController for unit testing 
    // (see https://www.natashatherobot.com/ios-testing-view-controllers-swift/ )
    let _ = alertWindow.rootViewController?.view
    alertWindow.makeKeyAndVisible()
    alertWindow.rootViewController!.presentViewController(self.alertController, animated: animated, completion: completion)
}
但是,在运行单元测试时alertWindow.makeKeyAndVisible(),我得到一个NSInternalInconsistencyException: props must have a valid clientID。
该代码在应用程序代码中有效,并且我不希望使用模拟UIWindow等,因为我希望验证警报是否真正显示在真实的 UIWindow上。
关于如何在单元测试中使用UIWindows()的任何指导?我究竟做错了什么?
问题是makeKeyAndVisible调用内部需要运行UIApplication实例的代码。这就是为什么在测试框架时而不是在测试应用程序时抛出异常的原因。应用程序测试将测试包注入正在运行的应用程序中。简单的解决方法是从:
alertWindow.makeKeyAndVisible()
至
alertWindow.isHidden = false
这可以正常工作,并允许视图控制器与窗口隔离进行测试。缺点是当然的,这是不相同的,以makeKeyAndVisible-它不会有副作用,引发异常。
另一种策略是专门创建一个新的空应用程序目标以支持测试。将要测试的框架嵌入其中,并将其用作单元测试的宿主应用程序。
| 归档时间: | 
 | 
| 查看次数: | 1199 次 | 
| 最近记录: |