View Controller TDD

风格不统一 提交于 2019-11-30 08:54:37

I agree with @MikeTaverne's answer: I prefer accessing -[UIViewController view] in order to trigger -[UIViewController viewDidLoad], rather than calling it directly. See if the test failures for FirstViewController go away once you use this instead:

viewController = navigationController.topViewController as FirstViewController
let _  = viewController.view

I'd also recommend giving both view controllers identifiers in your storyboard. This will allow you to instantiate them directly, without accessing them via UINavigationController:

var secondViewController: SecondViewController!

override func setUp() {
    let storyboard = UIStoryboard(name: "Main", bundle: NSBundle(forClass: self.dynamicType))
    secondViewController = storyboard.instantiateViewControllerWithIdentifier("SecondViewController")
        as SecondViewController
    let _ = secondViewController.view
}

Check out my talk on testing UIViewController at Brooklyn Swift for details: https://vimeo.com/115671189#t=37m50s (my presentation begins around the 37'50" mark).

Mike Taverne

I've begun unit testing view controllers recently, and it poses some unique challenges.

One challenge is getting the view to load. Looking at your set up for FirstViewController, you are trying to do this with viewController.viewDidLoad().

My suggestion is to replace that line with this:

let dummy = viewController.view

Accessing the .view property will force the view to load. This will trigger the .viewDidLoad in your ViewController, so don't call that method explicitly in your test.

This approach is considered hacky by some people, but it is simple and effective. (See Clean way to force view to load subviews early)

As an aside, I am finding the best way to test view controllers is to move as much code out of the view controllers as possible into other classes that are more easily tested.

If your view controller is defined in a storyboard, then you need to instantiate it that way for your outlets to be set up properly. Trying to initialize it like an ordinary class won't work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!