简体   繁体   中英

how to unit test UIApplication extension

Suppose I use this code that extracts the top most viewController

import UIKit

extension UIApplication {
    
    class func topViewController(_ base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        
        if let navigationController = base as? UINavigationController, navigationController.viewControllers.count > 0 {
            return topViewController(navigationController.visibleViewController)
        }
        
        if let tabBarController = base as? UITabBarController {
            if let selected = tabBarController.selectedViewController {
                return topViewController(selected)
            }
        }
        
        if let presentedViewController = base?.presentedViewController {
            return topViewController(presentedViewController)
        }
        
        return base
    }
    
}

How do I facilitate unit testing of this code? I would need to use an instance of UIApplication.shared . Any tips would be appreciated.

If instead this was an extension to UIViewController, you could omit the parameter ( base ) altogether.

The call would then change to

let top = UIApplication.shared.keyWindow?.rootViewController.topViewController()

In order to unit test this, we can simply create a ViewController and perform our tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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