简体   繁体   English

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(_:)))
    }
}

I have this class above, and I need to create an XCTestCase for this class and make all code coverage. 我上面有这个类,我需要为这个类创建一个XCTestCase并进行所有代码覆盖。 In XCTestCase I need to call viewDidLoad(), close() and setNavBar() functions, how can do this correctly? 在XCTestCase中,我需要调用viewDidLoad(),close()和setNavBar()函数,如何正确执行此操作?

Is it possible using a mock framework for my class in swift ? 是否可以在我的课程中快速使用模拟框架? How can do this ? 怎么办呢?

You can trigger the call of viewDidLoad() by accessing the view property of the controller in the test: 您可以通过在测试中访问控制器的view属性来触发对viewDidLoad()的调用:

_ = viewController.view

For the call of the other method, I would call them directly. 对于其他方法的调用,我将直接调用它们。

客观地讲,更干净的加载视图的方法是调用loadViewIfNeeded例如:

viewController.loadViewIfNeeded()

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

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