Can Swift Macro be tested with Swift Testing?

Hi,

Overview

When I try to create a new macro using Xcode, I couldn't see an option to select Swift Testing

Steps followed:

  1. In Xcode, New Package > Macro (template)
  2. Testing System drop down has only XCTest and no Swift Testing

However choosing a different template shows the option to select XCTest and Swift Testing

Questions

  1. Is macro testing possible using Swift Testing?
    1.1. If it is possible how do I use Swift Testing for macro?
    1.2. If it is possible, would it make sense to add Swift Testing to the drop down?
    1. Is creating macro even possible without creating a Swift Package?

Pardon my ignorance I am just starting to explore Swift macro.

  1. Is macro testing possible using Swift Testing?

Yes, I use swift-testing for my macro MetaCodable.

1.1. If it is possible how do I use Swift Testing for macro?

You can have a look at this invocation here. You basically have to use assertMacroExpansion API and pass the error to swift testing Issue.record API.

1.2. If it is possible, would it make sense to add Swift Testing to the drop down?

I think this is more of Xcode issue than a Swift issue. For this you might have to communicate to Apple with feedback assistant.

    1. Is creating macro even possible without creating a Swift Package?

I created a guide for distributing macro with CocoaPods. Is this something you are looking for?

1 Like

Thanks a lot @soumyamahunt for the detailed response, was very helpful.

Changes for using Swift Testing

  • Edit the Test file
  • Change import XCTest to import Testing
  • Change final class MyMacroTests: XCTest to struct MyMacroTests
  • Annotate the test functions with @Test
  • It seems so obvious now :D but I completely missed it :smiley:

Reason for asking about not using SPM

  • Reason for asking if macros was possible if Swift macros was possible without SPM was because I was wondering if I can create a macro in my main project without a separate swift package.
  • As I type I realise that I have to add a dependency to swift-syntax and its best to keep this dependency isolated and its nicer to have the macro in the swift package so that it is tested inside the package and neatly isolated away from the rest of the project.
  • Thanks a lot for writing the blog post, though I wouldn't be using it with cocoapods it definitely gives a perspective on the dependencies.
  • So I think for my needs SPM fits well

Xcode Feedback

Feedback: FB15359551

1 Like