How to test for viewDidLoad in iOS

Issue #52

Suppose we have the following view controller

1
2
3
4
5
6
class ListController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
}
}

Get to know viewDidLoad

We know that viewDidLoad is called when view is created the first time. So in the the Unit Test, if you use viewDidLoad to trigger, you will fall into a trap

1
2
3
4
func testSetup() {
let controller = ListController()
controller.viewDidLoad()
}

Why is viewDidLoad called twice?

  • It is called once in your test
  • And in your viewDidLoad method, you access view, which is created the first time, hence it will trigger viewDidLoad again

The correct way

The best practice is not to trigger events yourself, but do something to make event happen. In Unit Test, we just access view to trigger viewDidLoad

1
2
3
4
func testSetup() {
let controller = ListController()
let _ = controller.view
}

Comments