Skip to content

Instantly share code, notes, and snippets.

@brennanMKE
Last active February 6, 2025 19:31
Show Gist options
  • Save brennanMKE/17f8ba5bc2210ae4d3123169649932dc to your computer and use it in GitHub Desktop.
Save brennanMKE/17f8ba5bc2210ae4d3123169649932dc to your computer and use it in GitHub Desktop.
Actor isolation in unit tests

Actor isolation in unit tests

Automated tests with actors can result in using await across many lines which is a lot of lock/unlock cycles which can have some unwanted side effects. In the very least it can just make your unit tests run more slowly. I wanted to see how I could set up my tests to evaluation expectations within the isolated actor scope. I found I could use an isolated parameter with a block to do it. See the code snippet for the function below.

private func run(_ actorInstance: <#actor type#>,
                 block: @Sendable (isolated <#actor type#>) async -> Void) async {
    await block(actorInstance)
}

Then in a test it is not necessary to include multiple await statements to enter the isolated context repeatedly.

await run(state) { state in
    #expect(state.count == 1)
    #expect(state.names.contains("Funches")
}

This works by running the block in the isolated context of the actor due to the isolated parameter of the block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment