Swift
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Optionals
-
Section 4: Object-Oriented and Value Types
-
Section 5: Memory Management
-
Section 6: Generics and Error Handling
-
Section 7: Concurrency
-
Section 8: Working with Collections
-
Section 9: Codable and Data Handling
-
Section 10: Protocol-Oriented Programming
-
Section 11: Testing and Tooling
-
Section 12: Practical Projects
-
Section 13: Interview Practice
-
Section 14: More Practice Exercises
-
Section 15: More Standard Library
-
Section 16: Advanced Concurrency
-
Section 17: Foundation Framework Deep Dive
-
Section 18: URLSession and Networking Deep Dive
-
Section 19: Combine Framework
-
Section 20: SwiftUI Fundamentals for Swift Developers
-
Section 21: Server-Side Swift with Vapor
-
Section 22: Swift Package Manager Deep Dive
-
Section 23: Swift Concurrency Deep Dive
-
Section 24: More Language Features
-
Section 25: Error Handling Deep Dive
-
Section 26: Testing Deep Dive
-
Section 27: Data Structures and Algorithms in Swift
-
Section 28: More Practice Exercises
-
Section 29: More Interview Practice
-
Section 30: Swift Macros (Swift 5.9+)
-
Section 31: Property Wrappers Ecosystem
-
Section 32: Swift Interop Deep Dive
-
Section 33: iOS App Architecture Patterns
-
Section 34: Performance and Debugging
-
Section 35: App Distribution and CI/CD
-
Section 36: More Practical Projects
-
Section 37: SwiftData and Persistence
-
Section 38: More Design Patterns
-
Section 39: More Review and Practice
-
Section 40: More Foundation Deep Dive
-
Section 41: Advanced Collections in Swift
-
Section 42: Advanced Generics Practice
-
Section 43: UIKit for Legacy and Hybrid Apps
-
Section 44: watchOS and visionOS Development Basics
-
Section 45: More Networking Patterns
-
Section 46: More Testing Practice
-
Section 47: Accessibility in Swift Apps
-
Section 48: Localization
-
Section 49: More Practical Projects Round 2
-
Section 50: Swift Charts Framework
-
Section 51: More Interview and Algorithm Practice
-
Section 52: Final Practice and Mastery
-
Section 53: Swift Compiler and Build System
-
Section 54: More Concurrency Practice
-
Section 55: App Store Guidelines and Review
-
Section 56: More Design and Architecture
47: Unit Testing with XCTest
You've written a lot of code by now, and probably spent a fair amount of time manually running your app, clicking a button, and checking if the result is what you expected. That works for a tiny project, but once your app grows, that process becomes a nightmare. You change one line of code in a helper method and suddenly three other screens are crashing, and you have no idea why.
This is where XCTest comes in. It's not just about "checking if it works"—it's about creating a safety net. I want you to think of unit tests as documentation that actually executes. If a new developer (or you, six months from now) breaks something, the test will scream at them immediately.
Creating a ShoppingCart to break
Let's build something concrete. I'm going to create a ShoppingCart class. In a real app, this would probably interact with a database or an API, but for unit testing, we want to test the logic in isolation. I'll keep it simple: it should hold products and calculate a total.
struct Product {
let name: String
let price: Double
}
class ShoppingCart {
private(set) var items: [Product] = []
func add(product: Product) {
items.append(product)
}
func calculateTotal(discountCode: String? = nil) -> Double {
let subtotal = items.reduce(0) { $0 + $1.price }
if discountCode == "SAVE10" {
return subtotal * 0.9
}
return subtotal
}
}
Our first XCTAssertEqual
To test this, we need a class that inherits from XCTestCase. I usually name my test classes by appending "Tests" to the class I'm testing. I'm going to write a test to make sure that adding items actually increases the total. I'm using XCTAssertEqual here because I have a very specific expected outcome.
import XCTest
@testable import MyStoreApp
class ShoppingCartTests: XCTestCase {
func testCalculateTotal_withMultipleItems_returnsCorrectSum() {
// Arrange
let cart = ShoppingCart()
cart.add(product: Product(name: "Swift Book", price: 30.0))
cart.add(product: Product(name: "Coffee Mug", price: 15.0))
// Act
let total = cart.calculateTotal()
// Assert
XCTAssertEqual(total, 45.0, "The total should be the sum of all item prices.")
}
}
Notice the "Arrange, Act, Assert" pattern. I'm a stickler for this. It keeps your tests readable. Arrange your data, act on the method you're testing, and assert that the result is correct.
Fixing a logic bug in the discount flow
Now, let's say I want to add a tax calculation. I'll quickly update my calculateTotal method to add a 10% tax. I'll be honest—I'm rushing this part, which is exactly how bugs happen.
func calculateTotal(discountCode: String? = nil) -> Double {
let subtotal = items.reduce(0) { $0 + $1.price }
let totalWithTax = subtotal * 1.1
if discountCode == "SAVE10" {
return totalWithTax * 0.9
}
return totalWithTax
}
Wait. I just realized I've made a business logic error. In most jurisdictions, discounts are applied to the subtotal before tax is calculated, not to the final taxed amount. If I run my tests now, I might not notice if I only tested the basic sum. Let's write a test specifically for the discount to see if the math feels right.
func testCalculateTotal_withDiscount_appliesDiscountBeforeTax() {
let cart = ShoppingCart()
cart.add(product: Product(name: "Keyboard", price: 100.0))
// Expected: (100 * 0.9) * 1.1 = 99.0
let total = cart.calculateTotal(discountCode: "SAVE10")
XCTAssertEqual(total, 99.0, "Discount should be applied before tax.")
}
If I run this, it might actually pass because the math (100 * 1.1) * 0.9 also equals 99. My mistake was thinking the order didn't matter. But if the tax was a flat fee or a different percentage, this would fail miserably. I'll rewrite the logic to be explicit about the order of operations so it's maintainable.
func calculateTotal(discountCode: String? = nil) -> Double {
let subtotal = items.reduce(0) { $0 + $1.price }
var discountedSubtotal = subtotal
if discountCode == "SAVE10" {
discountedSubtotal = subtotal * 0.9
}
return discountedSubtotal * 1.1
}
Ensuring a clean state for every test
As I add more tests, I'm realizing I'm typing let cart = ShoppingCart() in every single function. It's tedious. I'll move that to the setUp method. XCTest calls setUp() before every single test method, ensuring that each test starts with a fresh, empty cart. This prevents "test pollution," where one test fails because a previous test left something in the cart.
class ShoppingCartTests: XCTestCase {
var cart: ShoppingCart!
override func setUp() {
super.setUp()
cart = ShoppingCart()
}
override func tearDown() {
cart = nil
super.tearDown()
}
func testEmptyCartReturnsZero() {
XCTAssertEqual(cart.calculateTotal(), 0.0)
}
// ... other tests now use the shared 'cart' instance
}📋 Practical Task
Exercise: Testing the Loyalty Points Calculator
You are tasked with implementing and testing a LoyaltyProgram class. The business rules are as follows:
- Users earn 1 point for every $10 spent.
- If a user spends over $100 in a single transaction, they get a "Bonus" of 20 extra points.
- Points should always be rounded down (integers).
Your Task:
- Create the
LoyaltyProgramclass with a methodcalculatePoints(for amount: Double) -> Int. - Create a
LoyaltyProgramTestsclass usingXCTestCase. - Write three distinct tests:
- One that verifies a standard purchase (e.g., $50 returns 5 points).
- One that verifies the bonus is applied correctly for purchases over $100 (e.g., $110 returns 11 + 20 = 31 points).
- One that verifies that amounts under $10 return 0 points.
There are no comments for now.