DEV Community

Khoa Pham
Khoa Pham

Posted on

2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more