简体   繁体   English

Swift-单元测试中的依赖注入

[英]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 : 这是我第一次快速使用依赖项注入,这就是我的方法,我有一个在appDelegate中初始化的dataManager,然后传递给我的第一个视图控制器,然后每当它们被推到其他视图控制器时,它将传递给其他视图控制器屏幕:

  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. 现在,一切正常,但是当我测试每个视图控制器时,我总是使dataManger为零,并且我知道这是因为我首先给出的条件。 So is there way to make sure the topViewController always has dataManager variable without inheriting from another ViewController.Thank you 因此,有没有办法确保topViewController始终具有dataManager变量而不继承自另一个ViewController。谢谢

One of these is happening: 其中之一正在发生:

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

It should be a simple debug. 它应该是一个简单的调试。 Either put some breakpoints and/or print statements to know where the problem is. 放置一些断点和/或print语句以了解问题出在哪里。

Tip(s): 提示):

  • Make sure to set the view controller's class correctly in XCode/Interface-Builder. 确保在XCode / Interface-Builder中正确设置视图控制器的类。

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

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