Search code examples
iosswiftmockingxctestxctestcase

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. In XCTestCase I need to call viewDidLoad(), close() and setNavBar() functions, how can do this correctly?

Is it possible using a mock framework for my class in swift ? How can do this ?


Solution

  • You can trigger the call of viewDidLoad() by accessing the view property of the controller in the test:

    _ = viewController.view
    

    For the call of the other method, I would call them directly.