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 outputassertMacroExpansion
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]
)
}
}