0Pricing
Swift Academy · Lesson

Testing and Debugging Macros

Writing unit tests for macro expansions using assertMacroExpansion.

Why Test Macros?

Macros generate code at compile time. Unit tests verify the generated source before it reaches production.

// The swift-syntax package ships SwiftSyntaxMacrosTestSupport
// with assertMacroExpansion for testing macro output

assertMacroExpansion

assertMacroExpansion takes input source and expected expanded source and verifies they match.

import SwiftSyntaxMacrosTestSupport
import XCTest

final class StringifyMacroTests: XCTestCase {
  func testStringify() throws {
    assertMacroExpansion(
      "#stringify(1 + 2)",
      expandedSource: "(1 + 2, \"1 + 2\")",
      macros: ["stringify": StringifyMacro.self]
    )
  }
}

All lessons in this course

  1. Macro Roles: Freestanding vs Attached
  2. Writing a Freestanding Expression Macro
  3. Attached Member Macros for Boilerplate Reduction
  4. Testing and Debugging Macros
← Back to Swift Academy