Adding tests
The principle of testing a macro is to test a code block before and after the macro expansion.
As part of our Swift Macros package, we have a test target (Figure 10.10):
Figure 10.10: A testing target for StructInitMacro
Each Swift package comes with a testing target, and in this case, we already have one test with the stringify
macro that comes when we create a new Swift Macros package.
Let’s clear the test file and start our own test.
To test a macro, we need to create the XCTestCase
subclass and create a new method called testMacro
. Remember that test functions in XCTest
always start with the phrase “test” followed by the test name.
To test a macro expansion, we will use a particular SwiftSyntax
function called assertMacroExpansion
. The most important function parameters are as follows:
_originalSource
: The original code before the expansion, including the macro attribute itselfexpandedSource...