joshw
(Josh)
December 8, 2024, 6:51pm
1
Using XCTest I can have a func tearDown() async throws however with swift-testing, we are forced to do teardown logic in the deinit, which supports neither throwing nor async code.
What's the best way to run some common async teardown logic after each test using swift-testing?
1 Like
joshw
(Josh)
December 8, 2024, 7:11pm
2
It looks like this is an active discussion here .
Looking forward to this landing, @smontgomery !
0xTim
(Tim)
December 8, 2024, 11:16pm
3
The other option is the withXXX approach we're using in Vapor, works well with structured concurrency
joshw
(Josh)
December 9, 2024, 1:59am
4
Have a link to an example? Did a cursory search in the vapor repo but couldn't find what you're referring to.
ptoffy
(Paul Toffoloni)
December 9, 2024, 9:36am
5
3 Likes
For posterity’s sake, here’s how you can do it in Swift 6.1 and later:
struct AsyncTeardownTrait: TestTrait, TestScoping {
func provideScope(
for test: Test,
testCase: Test.Case?,
performing function: () async throws -> Void
) async throws {
try await function()
// Replace with your teardown logic.
try await tearDown()
}
}
extension Trait where Self == AsyncTeardownTrait {
static var asyncTeardown: Self { Self() }
}
@Test(.asyncTeardown)
func doStuffWithAsyncTeardown() {
// Test stuff.
}
One thing I’m not sure about is how to pass state from the test suite to the async teardown with this approach.
stumbler
(Stumbler)
October 9, 2026, 5:28am
7
Thanks this helps me also