Today Swift 5.9 is officially released, bringing macros to the language. Macros are a powerful
feature that allow you to implement functionality in the language as if it was built directly into
the language. However, they can be tricky to get right, and as such one needs to write an extensive
test suite to make sure you have covered all of the subtle and nuanced edge cases that are
possible.
Today we are excited to announce MacroTesting, a brand new tool for testing
macros in Swift that is simple to use and powerful. It allows you to assert on every aspect of
your macros, including expanded source, diagnostics, fix-its, and more.
Join us for a quick overview of the library, or watch this week’s free episode
to see what our library has to offer and how it greatly improves upon the tools Apple provides.
Using MacroTesting
After adding MacroTesting to your project and importing it into your test file, there is one
primary tool for testing: assertMacro
. This function is similar to the
assertMacroExpansion
function that comes with
SwiftSyntax, but our function does not require you to specify the source string
that the macro expands to.
For example, suppose you had an @AddCompletionHandler
macro that
can be applied to any async
method in order to generate an equivalent callback-based method. To
test this we merely have to specify the input source string that we want to expand:
func testAddAsyncCompletionHandler() {
assertMacro(["AddCompletionHandler": AddCompletionHandlerMacro.self]) {
"""
struct MyStruct {
@AddCompletionHandler
func f(a: Int) async -> String {
return b
}
"""
}
}
Just that little bit of code is already compiling with our library. But, the first time you run
this test, the macro will be automatically expanded and inserted into the test for you:
func testAddAsyncCompletionHandler() {
assertMacro {
"""
struct MyStruct {
@AddCompletionHandler
func f(a: Int) async -> String {
return b
}
}
"""
} matches: {