Swift (iOS) 代码覆盖率和 XCTest(模拟)

Swift (iOS) code coverage and XCTest (mock)

  class MyClassVC: UIViewController {

    var html : String?
    var heightBar: CGFloat?
    var webView: UIWebView?

    override func viewDidLoad() {
      super.viewDidLoad()

      heightBar = self.navigationController?.navigationBar.frame.height

      webView = UIWebView(frame: CGRect(x: self.view.frame.origin.x, y: self.view.frame.origin.y, width: self.view.frame.width, height: self.view.frame.height - heightBar!))

      let resources = NSBundle.mainBundle().pathForResource("example", ofType: "html")
      let css = NSURL(fileURLWithPath: resources!)

      webView!.loadHTMLString(html!, baseURL: css)

      setNavBar()

      self.view.addSubview(webView!)
    }

    func close(sender: UIBarButtonItem){
      dismissViewControllerAnimated(true, completion: nil)
    }

    func setNavBar(){
      var title : NSDictionary = Dictionary<NSObject,AnyObject>();
      title = [NSFontAttributeName:UIFont.systemFontOfSize(20), NSForegroundColorAttributeName: UIColor(netHex: AppColors().getAppColors("colors"))]
      self.navigationController!.navigationBar.titleTextAttributes = title as? [String : AnyObject]

      navigationItem.rightBarButtonItem = UIBarButtonItem( title: "Close", style: .Plain, target: self, action: #selector(MyClassVC.close(_:)))
    }
}

我上面有这个 class,我需要为此 class 创建一个 XCTestCase 并覆盖所有代码。 在 XCTestCase 中,我需要调用 viewDidLoad()、close() 和 setNavBar() 函数,如何正确执行此操作?

是否可以在 swift 中为我的 class 使用模拟框架?怎么能做到这一点?

您可以通过访问测试中控制器的视图属性来触发viewDidLoad()的调用:

_ = viewController.view

其他方法的调用,我直接调用。

客观地说,更简洁的加载视图的方法是调用 loadViewIfNeeded,例如:

viewController.loadViewIfNeeded()