Zum Hauptinhalt springen
tsecurity.de LIVE
Echtzeit-Radar & Feeds
Alle RSS Feeds
👥 Community & Social
Sichere ProgrammierungThe Model Got Better. Your Judgment Got Worse.(22.09.2026 um 03:02 Uhr)
Sichere ProgrammierungAIFeed - signed content permissions for AI web crawlers(22.09.2026 um 03:10 Uhr)
Sichere ProgrammierungThanks, glad you liked it!(22.09.2026 um 03:15 Uhr)
Sichere ProgrammierungA request for /.env shouldn't render your React app(22.09.2026 um 03:17 Uhr)
Sichere ProgrammierungAI-Agent Marketplaces Need Verifiable Delivery, Not More Listings(22.09.2026 um 03:20 Uhr)
AI & KI NachrichtenBeyond Bigger Models: Toward a Modular Cognitive Architecture(22.09.2026 um 03:21 Uhr)
Sichere ProgrammierungMasa Depan Manajemen Data: Mengenal Konsep Data Mesh yang Revolusioner(22.09.2026 um 03:22 Uhr)
Sichere ProgrammierungHow to Search Your Claude Code Conversation History(22.09.2026 um 03:22 Uhr)
Sichere ProgrammierungThe Model Got Better. Your Judgment Got Worse.(22.09.2026 um 03:02 Uhr)
Sichere ProgrammierungAIFeed - signed content permissions for AI web crawlers(22.09.2026 um 03:10 Uhr)
Sichere ProgrammierungThanks, glad you liked it!(22.09.2026 um 03:15 Uhr)
Sichere ProgrammierungA request for /.env shouldn't render your React app(22.09.2026 um 03:17 Uhr)
Sichere ProgrammierungAI-Agent Marketplaces Need Verifiable Delivery, Not More Listings(22.09.2026 um 03:20 Uhr)
AI & KI NachrichtenBeyond Bigger Models: Toward a Modular Cognitive Architecture(22.09.2026 um 03:21 Uhr)
Sichere ProgrammierungMasa Depan Manajemen Data: Mengenal Konsep Data Mesh yang Revolusioner(22.09.2026 um 03:22 Uhr)
Sichere ProgrammierungHow to Search Your Claude Code Conversation History(22.09.2026 um 03:22 Uhr)
Intelligence View
⚡ tsecurity.de Intelligence

Running Asynchronous Setup Side Effects in `@Test` with Swift Testing

🧩 Introduction Sometimes in test code, we want to perform side effects just before a test case runs — without placing that setup logic directly inside the test function. Swift Testing supports Arrange phases before a test, but it does…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!




🧩 Introduction



Sometimes in test code, we want to perform side effects just before a test case runs — without placing that setup logic directly inside the test function.



Swift Testing supports Arrange phases before a test, but it doesn’t (yet) allow asynchronous or side-effectful setup directly in @Test.



Sure, helper functions work — but what if we could express Arrange–Act–Assert (AAA) visibly and cleanly inside Swift Testing itself?



If you have suggestions for improvements, feel free to comment.









🎯 Goal



Here’s what we’d like to achieve:




// MARK: - Test case and its preparation
@Test(
// MARK: Arrange
// Ideally, asynchronous side effects could run here
)
func testCase1() async throws {
// MARK: Action
// MARK: Assertion
}






In short, this post shows that — yes, you can do this.

@Test already supports parameterized tests, so we can leverage that mechanism to perform async setup work.





💡 Motivation



You might think:



“You could already do this using TestTrait or TestScoping’s setUp().”



And yes — you’d be right. But I wanted per-test asynchronous setup, not a global one.



Example: testing a “read” operation might require writing data first. I want that Write to live right next to the test that reads it — not far away in a shared helper.



Of course, helper functions are an option, but they separate intent and context. I wanted my test’s Arrange to be visually and contextually adjacent to the test logic itself.





🧩 Example: Using Realm



Let’s look at a concrete example using Realm.



Realm is common in iOS apps, but it can behave unexpectedly across threads.

Testing concurrency-heavy code with Realm requires careful context handling.

In particular, the in-memory configuration is sensitive to scope.



Here’s a test that demonstrates how to perform async setup directly via @Test:




@Test(MyTestTrait(
actions: [ // Perform pre-test side effects here
{ realm in
print("Arrange Step 1:", realm, Thread.current)
},
{ realm in
// Another example — not always necessary
print("Arrange Step 2:", realm, Thread.current)
}
]
))
func example() async throws {
guard let realm = RealmContext.current?.realm else {
XCTFail("Realm not injected")
return
}

// Perform Realm tests
print("🧪 Using realm:", realm, Thread.current)
}









🧩 TaskLocal Context



We can define a TaskLocal context to safely inject the Realm instance:




struct RealmContext {
@TaskLocal static var current: RealmContext?
let realm: RLMRealm
}






This allows RealmContext.current to be available anywhere inside the async test body.






⚙️ Implementing the Trait



Here’s a minimal MyTestTrait implementation that performs setup and cleanup around the test body:




struct MyTestTrait {
// These actions are passed in from the test
let actions: [@Sendable (RLMRealm) async throws -> ()]
}

extension MyTestTrait: TestTrait, TestScoping {
func provideScope(
for test: Test,
testCase: Test.Case?,
performing function: @Sendable () async throws -> ()
) async throws {

// Setup Realm (in-memory)
let realm = {
let config = RLMRealmConfiguration.default()
config.inMemoryIdentifier = UUID().uuidString
RLMRealmConfiguration.setDefault(config)
return RLMRealm.default()

// NOTE: This modifies the global .default configuration.
// It can leak into other tests, so use with caution.
}()

// Execute Arrange steps sequentially
for action in actions {
try await action(realm)
}

// Run the test body within the scoped context
try await RealmContext.$current.withValue(.init(realm: realm)) {
try await function()
}
}
}






This keeps setup logic close to your test definition,

while still leveraging Swift Testing’s structured concurrency and scoping.






🧩 Takeaways




  • ✅ You can use parameterized traits to perform async setup directly in @Test

  • ✅ TaskLocal makes dependency injection ergonomic and thread-safe

  • ⚠️ Beware: changing Realm’s global configuration can leak between tests

  • 🚫 localActions = actions–style “safety copies” are unnecessary; traits aren’t shared across tests

  • 🧠 Prefer direct initializers to redundant static factories






Notes




  • Tested on Swift 6.1, Xcode 16.3

  • RLMRealm is not Sendable — protect access carefully

  • For projects using DI frameworks, this approach may overlap with existing patterns

  • Yes, whether you should test side effects is a valid philosophical question

Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Running Asynchronous Setup Side Effects in `@Test` with Swift Testing

Thematisch verwandte Begriffe: Running, Asynchronous, Setup, Side · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-49449 | Joplin is an open source note-taking and to-do application that organise…
Advisory →
TTS Reader • tsecurity.de Voice
tsecurity.de Icon
tsecurity.de App
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag
Themen-Radar & Intelligence Matrix
Echtzeit-Taxonomie nach Angriffsvektoren & Plattformen

tsecurity.de Live Threat Radar

🔴 LIVE RADAR
MONITORING
AKTIV
CVE-DATENBANK
LIVE
🔍
Community Radar & Live Chat
Sentinel Bot online • Live-Stream
Dein Cluster: Security Explorer
Match:
lädt…
Verbindung zum Community-Stream wird aufgebaut...
Bearbeitungsmodus — Senden überschreibt deine Nachricht
Community-Puls — was gerade passiert
lädt…
Aktivitäten deiner Analysten
lädt…
Neues Thema oder Eilmeldung einreichen

Reiche interessante Links, Zero-Days oder Debatten ein. Die Community entscheidet per Upvote über die Veröffentlichung.

Heiß diskutierte Einreichungen
🔖 Gespeicherte Artikel
📂 Keine gespeicherten Artikel vorhanden.
Zurück Ziehen Vor
Links: vorheriger Artikel Rechts: nächster Artikel unten: schließen
News NIS-2 Frühwarnung Tier-1 Intel ⏱️ 3 Min vor 10 Min
Artikeldaten werden geladen...

Zurück: vorheriger Vor: nächster
↗ Original-Quelle
Social Reaktionen Deine Reaktion zählt
Einstufung & Relevanz-Poll 0 Stimmen
In sozialen Netzwerken teilen 1-Klick