【问题标题】:Swift (iOS) code coverage and XCTest (mock)Swift (iOS) 代码覆盖率和 XCTest (mock)
【发布时间】:2016-10-07 14:13:51
【问题描述】:
  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(_:)))
    }
}

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

是否可以在 swift 中为我的班级使用模拟框架?怎么会这样?

【问题讨论】:

  • 为什么要模拟类?

标签: ios swift mocking xctest xctestcase


【解决方案1】:

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

_ = viewController.view

对于其他方法的调用,我会直接调用它们。

【讨论】:

    【解决方案2】:

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

    viewController.loadViewIfNeeded()
    

    【讨论】:

      猜你喜欢
      • 2016-08-23
      • 1970-01-01
      • 2018-01-11
      • 2017-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多