Back to course overview
Module 6Testing & debugging with AI 14 min

Writing tests with AI

Add automated tests for your logic so future changes (yours or the AI's) can't silently break what works.

Tests are how you stop fixing the same bug twice. They're also how you safely let AI refactor your code: if the tests still pass, the behavior is intact. You don't need to test everything — test the logic that would hurt if it broke.

What's worth testing in DayOne

  • The String.firstLine helper — pure logic, easy to get subtly wrong.
  • Decoding Insights from a sample JSON string — proves your struct matches the model's output.
  • The 'Save is disabled when empty' rule — a behavior your users rely on.
DayOneTests.swiftswift
import Testing
@testable import DayOne

struct DayOneTests {
    @Test func firstLineReturnsFirstLine() {
        #expect("Hello\nWorld".firstLine == "Hello")
        #expect("".firstLine == "Untitled")
    }

    @Test func decodesInsightsJSON() throws {
        let json = #"{"title":"A quiet win","mood":"calm","reflection":"What helped?"}"#
        let insights = try JSONDecoder().decode(Insights.self, from: Data(json.utf8))
        #expect(insights.mood == "calm")
    }
}

This uses Swift Testing (the modern #expect style). Each @Test function checks one claim. Run them with ⌘U — green means the claim holds. If you later change firstLine and it breaks, the test fails loudly instead of the bug reaching users.

Prompt to try

Using Swift Testing (the #expect macro; requires Xcode 16 or newer), write focused unit tests for this function and this Decodable struct: [paste firstLine + Insights]. Cover empty input, multi-line input, and malformed JSON. Keep each test to one assertion where possible.

Swift Testing ships with the Xcode toolchain, not the OS — you need Xcode 16 or newer. On an older Xcode, ask your assistant for the equivalent XCTest tests instead.

Tests are AI's safety net too

Before you let a model refactor a file, make sure it has tests. Then the workflow is: ask for the refactor → run ⌘U → if green, keep it; if red, paste the failure back. Tests turn 'I hope the AI didn't break anything' into a two-second check.