S01E06: [TDD 🍅 5] Testing View Controllers in Swift

Will Saults
7 min readJan 6

Video Lesson

Last Session

Photo by Hal Gatewood on Unsplash

It’s time to start the UI

First, create a new Project called QuizApp using Storyboards and Swift. Don’t fret 😮‍💨, we’ll look at using SwiftUI in future sessions!

Next, follow these steps:

  1. Delete the ViewController.swift, Main.storyboard, and SceneDelegate.swift
  2. Add var window: UIWindow? to AppDelegate.swift
  3. Remove UISceneSession Lifecycle ( functions ) in AppDelegate
  4. In target QuizApp > Info remove Main storyboard file base name
  5. Update your Info.plist file to the following:

Our AppDelegate will look like this:

import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true

Now, build and run (⌘R) and you should have an application that compiles and launches a simulator with a black screen. 🎉

Start with a test!

Create a QuestionViewControllerTests.swift file under the unit test target.

import XCTest

class QuestionViewControllerTests: XCTestCase {}

We’ll start by writing a test to verify the correct question text is displayed as a header.

func test_viewDidLoad_rendersQuestionHeaderText() {
XCTAssertEqual(sut.headerLabel.text, "Q1")

In order to test ViewControllers we need first to invoke their view lifecycle so that they are in a ready state. This is the same process when displaying our UI on the device.

func test_viewDidLoad_rendersQuestionHeaderText() {

_ = sut.viewDidLoad // ❌ Don't do this!

XCTAssertEqual(sut.headerLabel.text, "Q1")
Will Saults

Staff Software Engineer, iOS dev mentor, agile champion, TDD advocate, and AR/VR enthusiast!