简体   繁体   中英

Swift - Dependency injection in unit test

This the first time am working with dependency injection in swift an this is how I do it , I have a dataManager that is initialized in appDelegate then passed to my first view controller witch will then be passed to other view controllers every time they get pushed to screen :

  if let navigationCtrl = window?.rootViewController as? UINavigationController {

        if let firstViewController = navigationCtrl.topViewController as? FirstViewController {
            firstViewController.dataManager = dataManager
        }
    }

Now doing this, everything works great, but when I go to test each view controller, I always get dataManger to be nil, and I know it's because of the condition I gave in the first place. So is there way to make sure the topViewController always has dataManager variable without inheriting from another ViewController.Thank you

One of these is happening:

  • window is nil
  • window?.rootViewController is not a UINavigationController
  • navigationCtrl.topViewController is not a FirstViewController
  • firstViewController.dataManager is nil

It should be a simple debug. Either put some breakpoints and/or print statements to know where the problem is.

Tip(s):

  • Make sure to set the view controller's class correctly in XCode/Interface-Builder.

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