Skip to Content
Course content

117: The Swift Testing Framework

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

Imagine you're running a high-end bakery. You have a recipe for a sourdough loaf that usually turns out great, but every now and then, a batch comes out flat or way too salty. You wouldn't just put every loaf in the window and hope for the best; you'd have a "tasting station" in the back. Before any bread leaves the kitchen, you check a few specific things: Is the crust golden? Is the crumb open? Does it smell tangy? If any of those checks fail, you don't ship the bread, and you know exactly which part of the process went wrong.

The new Swift Testing framework is exactly that tasting station for your code. In the past, we relied on XCTest, which felt a bit like filling out a rigid government form. Swift Testing is different. It's designed to be more expressive and integrated directly into the language using macros. Instead of following strict naming conventions (like starting every function with the word "test"), we now use attributes to tell Swift, "Hey, this specific function is a check."

Ditching the XCTest Boilerplate

In the old days, if you wanted to test a function, you had to subclass XCTestCase and name your methods testCalculateTotal(). It was clunky. With the Swift Testing framework, we use the @Test attribute. This tells the compiler that the function is a test case, regardless of what you name it. I personally love this because it lets us use descriptive names that actually explain the intent of the test.

Let's look at a real scenario. Suppose we're building a ShoppingCart that handles a 10% discount if the total is over $100. Here is how we'd write a test for that:

import Testing

struct ShoppingCart {
    var items: [Double]
    
    func calculateTotal() -> Double {
        let sum = items.reduce(0, +)
        return sum > 100 ? sum * 0.9 : sum
    }
}

@Suite struct ShoppingCartTests {
    @Test("Check that discounts are applied to expensive carts")
    func discountApplied() {
        let cart = ShoppingCart(items: [60.0, 50.0]) // Total 110
        let total = cart.calculateTotal()
        
        #expect(total == 99.0)
    }
    
    @Test("Check that no discount is applied to cheap carts")
    func noDiscount() {
        let cart = ShoppingCart(items: [20.0, 10.0])
        let total = cart.calculateTotal()
        
        #expect(total == 30.0)
    }
}

Notice the #expect macro. This replaces the old XCTAssertEqual. It's much more flexible because it can take almost any boolean expression. If the expression inside #expect is false, the test fails, and Swift provides a clear breakdown of what the value actually was versus what you expected.

Testing Multiple Scenarios without Repeating Yourself

One of the most annoying parts of testing is when you have five different inputs that should all produce the same kind of result. In XCTest, you'd either write five different functions or a messy for loop that stopped at the first failure. Swift Testing solves this with parameterized tests using the arguments parameter in @Test.

If we want to make sure our ShoppingCart handles various price points correctly, we can pass a list of values directly into the test function:

@Test("Verify totals for various cart amounts", arguments: [
    (items: [10.0, 10.0], expected: 20.0),
    (items: [50.0, 60.0], expected: 110.0 * 0.9),
    (items: [100.0, 1.0], expected: 101.0 * 0.9),
    (items: [], expected: 0.0)
])
func checkTotals(items: [Double], expected: Double) {
    let cart = ShoppingCart(items: items)
    #expect(cart.calculateTotal() == expected)
}

This is a game-changer. Swift will run this function four separate times, treating each pair of inputs and expectations as its own individual test. If the third case fails, the other three still run, and you'll see exactly which input caused the crash. It's like having a tasting panel where every single bite is logged individually.

Organizing with Suites and Tags

When your project grows, you don't want to run 2,000 tests every time you change a single line of code. You can wrap your tests in a @Suite (as I did in the first example) to group related tests. But for more granular control, you can use tags.

By adding tags: .critical or tags: .smokeTest to your @Test attribute, you can filter your test runs in Xcode. I usually tag my heavy integration tests—the ones that hit a database or a network—so I can skip them during a quick local build and only run them in the CI pipeline.




📋 Practical Task

Exercise: Validating a Shipping Cost Engine

You are tasked with testing a ShippingCalculator. The business logic is as follows:

  • Orders under 5kg cost $5.00 flat.
  • Orders between 5kg and 20kg cost $10.00.
  • Orders over 20kg cost $20.00.
  • Orders with 0kg or negative weight should throw an error or return a specific sentinel value (for this exercise, return -1.0).

Your Goal: Write a test suite using the Swift Testing framework that verifies these four conditions. You must use at least one parameterized test (using arguments:) to handle the weight brackets and separate @Test functions for the edge cases (like negative weight).

struct ShippingCalculator {
    func calculateCost(weight: Double) -> Double {
        if weight <= 0 { return -1.0 }
        if weight < 5 { return 5.0 }
        if weight <= 20 { return 10.0 }
        return 20.0
    }
}

Ensure your tests use #expect and descriptive names for the test functions.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.