Hi all ,
I'm exploring the new Swift Testing framework, and came across a behavior I'd like to confirm.
Let’s say I define a custom trait like this:
struct MyTrait: TestTrait, TestScoping {
let value: UUID = UUID()
func provideScope(
for test: Test,
testCase: Test.Case?,
performing function: @Sendable () async throws -> Void
) async throws {
print("Trait value:", value)
try await function()
}
}
And apply it like this:
@Suite("MySuite", MyTrait())
struct MyTests {
@Test func test1() { }
@Test func test2() { }
}
When I run the tests, both test1
and test2
print the same UUID
, meaning the same MyTrait
instance is reused — even though provideScope()
is called separately for each test.
However, if I attach MyTrait()
individually to each test, the UUID is different — which suggests a fresh trait instance is used per test.
My Question:
Is it expected behavior that:
- Traits applied at the
@Suite
level are created once and shared across all tests in the suite? - Even though
provideScope()
is called per test, all tests access the same stored properties?
If so, would the best practice be to:
- Avoid storing per-test data in suite-level trait properties?
- Use helper methods or closures to generate fresh values inside
provideScope()
?
Thanks for the clarification!