Skip to Content
Course content

47: Unit Testing with XCTest

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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:

  1. Create the LoyaltyProgram class with a method calculatePoints(for amount: Double) -> Int.
  2. Create a LoyaltyProgramTests class using XCTestCase.
  3. 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.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.