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 mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay