DEV Community

Khoa Pham
Khoa Pham

Posted on

Test for viewDidLoad

Original post https://github.com/onmyway133/blog/issues/52

Suppose we have the following view controller

class ListController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .white
  }
}
Enter fullscreen mode Exit fullscreen mode

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

func testSetup() {
  let controller = ListController()
  controller.viewDidLoad()
}
Enter fullscreen mode Exit fullscreen mode

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

func testSetup() {
  let controller = ListController()
  let _ = controller.view
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)