S01E06: [TDD 🍅 5] Testing View Controllers in Swift
--
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:
- Delete the
ViewController.swift
,Main.storyboard
, andSceneDelegate.swift
- Add
var window: UIWindow?
toAppDelegate.swift
- Remove
UISceneSession Lifecycle
( functions ) inAppDelegate
- In target
QuizApp > Info
removeMain storyboard file base name
- Update your
Info.plist
file to the following:
Our AppDelegate
will look like this:
import UIKit
@main
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")
}