Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactor: use per-test StateBag instead of shared static state
Replace the shared static List<string> with per-test context StateBag
storage. Each test gets its own isolated list, eliminating the race
condition at the root rather than working around it with [NotInParallel]
and type guards.

The type guard in the BeforeEvery hook is still needed (it fires for
all tests) but no longer protects shared mutable state.
  • Loading branch information
thomhurst committed Apr 3, 2026
commit cfb2fa80f760a166c90ba2d64c3ec070398a8111
21 changes: 10 additions & 11 deletions TUnit.Engine.Tests/HookExecutionOrderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,31 +13,30 @@ public static void GlobalSetup(TestContext context)
return;
}

HookExecutionOrderTests._executionOrder.Clear();
HookExecutionOrderTests._executionOrder.Add("BeforeEvery");
var order = context.StateBag.GetOrAdd<List<string>>("executionOrder", _ => []);
order.Add("BeforeEvery");
}
}

[NotInParallel]
public class HookExecutionOrderTests
{
internal static readonly List<string> _executionOrder = [];

[Before(Test)]
public void InstanceSetup()
{
_executionOrder.Add("Before");
var order = TestContext.Current!.StateBag.GetOrAdd<List<string>>("executionOrder", _ => []);
order.Add("Before");
}

[Test]
public void VerifyExecutionOrder()
{
_executionOrder.Add("Test");
var order = TestContext.Current!.StateBag.GetOrAdd<List<string>>("executionOrder", _ => []);
order.Add("Test");

// Verify that BeforeEvery runs before Before
_executionOrder.Count.ShouldBe(3);
_executionOrder[0].ShouldBe("BeforeEvery");
_executionOrder[1].ShouldBe("Before");
_executionOrder[2].ShouldBe("Test");
order.Count.ShouldBe(3);
order[0].ShouldBe("BeforeEvery");
order[1].ShouldBe("Before");
order[2].ShouldBe("Test");
}
}
Loading