Teach me Unit Testing with Swift
- User
Teach me Unit Testing with Swift
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Teach me Unit Testing with Swift
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Let's dive into Unit Testing with Swift. This guide will take you from the absolute basics to more advanced topics like asynchronous testing, complete with clear explanations and code examples.
A unit is the smallest testable piece of code in your application. This is often a single function or a method on a class/struct.
Unit Testing is the practice of writing code to automatically test these individual units. You write a "test" that calls your function with a specific input and then checks ("asserts") that the output is what you expect.
When you create a new project in Xcode, the easiest way to get started is to check the "Include Tests" box.
This creates two important things for you:
YourProjectNameTests folder (target) for your unit tests.YourProjectNameUITests folder (target) for UI tests (a different topic).If you have an existing project, you can add a test target by going to File > New > Target... and selecting "Unit Testing Bundle".
XCTestApple's testing framework is called XCTest. The key components you'll use are:
XCTestCase: Your test classes will subclass this. It provides the framework for writing and running tests.XCTestCase subclass that begin with the word test. Each test...() function is a single, independent test.XCTAssert...): These are functions that check if a condition is true. If the condition is false, the test fails.Let's test a simple Calculator struct.
Step 1: Create the Code to Test
In your main project folder (not the Tests folder), create a new Swift file named Calculator.swift.
// Calculator.swift
import Foundation
struct Calculator {
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func subtract(_ a: Int, _ b: Int) -> Int {
return a - b
}
}
Step 2: Create the Test File
Now, go to your YourProjectNameTests folder. You'll see a file already there. You can rename it to CalculatorTests.swift or create a new one.
Here is the content for CalculatorTests.swift:
// CalculatorTests.swift
import XCTest
@testable import YourProjectName // IMPORTANT: Replace with your project's name
class CalculatorTests: XCTestCase {
// A test method to check the add() function
func test_add_positiveNumbers_returnsCorrectSum() {
// Arrange: Set up your constants, variables, and the object you're testing.
let calculator = Calculator()
let num1 = 5
let num2 = 3
let expectedResult = 8
// Act: Execute the code you are testing.
let result = calculator.add(num1, num2)
// Assert: Check that the result is what you expected.
XCTAssertEqual(result, expectedResult, "The sum should be 8.")
}
func test_subtract_numbers_returnsCorrectDifference() {
// Arrange
let calculator = Calculator()
// Act
let result = calculator.subtract(10, 4)
// Assert
XCTAssertEqual(result, 6)
}
}
Let's break down the test_add... function:
@testable import YourProjectName: This special import statement makes the internal types and methods from your main app target accessible to your test target. Without it, you could only test public entities.class CalculatorTests: XCTestCase: Defines our test suite for the Calculator.func test...(): The test prefix tells Xcode that this is a runnable test. The name is descriptive, explaining exactly what is being tested.Calculator), define inputs (num1, num2), and define the expected output (expectedResult).add() method.XCTAssertEqual is one of many assertion functions. If result is not equal to expectedResult, the test will fail and print the optional message.In Xcode, you'll see small diamond icons in the gutter next to your class and test function declarations.
Cmd + U to run all tests in your project.Results:
XCTAssert FunctionsYou have a whole library of assertions at your disposal.
| Assertion | What it Checks |
|---|---|
XCTAssertEqual(a, b) | Checks that a is equal to b. |
XCTAssertNotEqual(a, b) | Checks that a is not equal to b. |
XCTAssertTrue(expression) | Checks that a boolean expression is true. |
XCTAssertFalse(expression) | Checks that a boolean expression is false. |
XCTAssertNil(expression) | Checks that an optional is nil. |
XCTAssertNotNil(expression) | Checks that an optional has a value. |
XCTAssertGreaterThan(a, b) | Checks that a > b. |
XCTAssertThrowsError(expression) | Checks that an expression throws an error. |
XCTFail("message") | Immediately fails the test with a message. |
setUp and tearDownOften, your tests will need the same setup. Instead of repeating the "Arrange" step in every test, you can use setUp and tearDown.
setUpWithError(): This method is called before every single test function in the class runs. It's perfect for creating a fresh instance of the object you're testing.tearDownWithError(): This method is called after every single test function. It's great for cleanup, like resetting state or deallocating objects.Let's refactor CalculatorTests:
// CalculatorTests.swift (Refactored)
import XCTest
@testable import YourProjectName
class CalculatorTests: XCTestCase {
var sut: Calculator! // "sut" stands for "System Under Test" - a common convention
override func setUpWithError() throws {
// This is called before each test.
// Put setup code here.
sut = Calculator()
}
override func tearDownWithError() throws {
// This is called after each test.
// Put teardown code here.
sut = nil
}
func test_add_positiveNumbers_returnsCorrectSum() {
// Arrange (partially done in setUp)
// Act
let result = sut.add(5, 3)
// Assert
XCTAssertEqual(result, 8)
}
func test_subtract_numbers_returnsCorrectDifference() {
// Act
let result = sut.subtract(10, 4)
// Assert
XCTAssertEqual(result, 6)
}
}
Now, each test gets its own clean, new Calculator instance, ensuring that tests don't interfere with each other.
What if your code has a completion handler or uses async/await? The test function might finish before your async code does, leading to a false pass.
XCTestExpectation is the solution.
Imagine a WeatherFetcher that fetches data from a network (we'll fake it with a delay).
// WeatherFetcher.swift
struct Weather { let degrees: Int }
class WeatherFetcher {
func fetch(completion: @escaping (Weather) -> Void) {
// Fake a 2-second network delay
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
let weather = Weather(degrees: 75)
completion(weather)
}
}
}
Here's how to test it:
// WeatherFetcherTests.swift
import XCTest
@testable import YourProjectName
class WeatherFetcherTests: XCTestCase {
func test_fetch_returnsWeatherAfterDelay() {
// 1. Arrange: Create an expectation
let expectation = self.expectation(description: "Fetching weather should complete and call the handler.")
let fetcher = WeatherFetcher()
var result: Weather?
// 2. Act: Call the asynchronous method
fetcher.fetch { weather in
result = weather
// 3. Fulfill the expectation inside the completion handler
expectation.fulfill()
}
// 4. Wait for the expectation to be fulfilled, with a timeout.
wait(for: [expectation], timeout: 3.0)
// 5. Assert: Now that we've waited, we can check the result.
XCTAssertNotNil(result)
XCTAssertEqual(result?.degrees, 75)
}
}
async/await (Swift 5.5+)Testing with async/await is much simpler. Just make your test function async.
// ModernFetcher.swift
class ModernFetcher {
func fetch() async -> Weather {
// Fake a delay
try? await Task.sleep(nanoseconds: 1_000_000_000) // 1 second
return Weather(degrees: 80)
}
}
// ModernFetcherTests.swift
class ModernFetcherTests: XCTestCase {
// Note the `async` keyword on the test function
func test_fetch_returnsWeather() async {
// Arrange
let fetcher = ModernFetcher()
// Act
let result = await fetcher.fetch()
// Assert
XCTAssertEqual(result.degrees, 80)
}
}
test_userIsLoggedIn_showsProfileScreen is much better than testLogin.You now have a solid foundation for unit testing in Swift. Start by writing tests for simple, pure functions (like in the Calculator) and gradually move to more complex objects. Happy testing