Skip to content

Commit c0320fe

Browse files
committed
Enhanced docu for Execution Hooks to show users how to distinguish between SetUp and OneTimeSetUp inside a Hook.
1 parent e0923a8 commit c0320fe

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

docs/articles/nunit/extending-nunit/Execution-Hooks.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,16 @@ Each hook receives a `HookData` instance:
4747

4848
Use these fields for logging, conditional logic, or adaptive cleanup.
4949

50+
## One-Time vs Per-Test Setup/TearDown
51+
52+
`BeforeEverySetUpHook`/`AfterEverySetUpHook` and `BeforeEveryTearDownHook`/`AfterEveryTearDownHook` run for both per-test and one-time setup/teardown. Inside a hook, the supported way to distinguish the two is the current test context: `Context.Test.IsSuite` is `true` for [OneTimeSetUp]/[OneTimeTearDown] (suite context) and `false` for [SetUp]/[TearDown] (test method context).
53+
54+
See [Example: One-Time vs Per-Test Setup/TearDown](#example-one-time-vs-per-test-setup-teardown) for a complete hook implementation.
55+
56+
## Example: One-Time vs Per-Test Setup/TearDown
57+
58+
[!code-csharp[ExecutionHookAttributeExample](~/snippets/Snippets.NUnit/ExecutionHookExamples.cs#OneTimeVsPerTestSetupTearDownExample)]
59+
5060
## Example: Measure Time for Setup
5161

5262
[!code-csharp[ExecutionHookAttributeExample](~/snippets/Snippets.NUnit/ExecutionHookExamples.cs#TimingHookAttribute)]

docs/snippets/Snippets.NUnit/ExecutionHookExamples.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,24 @@ public override void AfterEverySetUpHook(HookData hookData)
3030
}
3131
#endregion
3232

33+
#region OneTimeVsPerTestSetupTearDownExample
34+
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
35+
public sealed class OneTimeVsPerTestSetupTearDownHookAttribute : ExecutionHookAttribute
36+
{
37+
public override void BeforeEverySetUpHook(HookData data)
38+
{
39+
var scope = data.Context.Test.IsSuite ? "OneTimeSetUp" : "SetUp";
40+
TestContext.Progress.WriteLine($"{scope}: {data.HookedMethod?.Name}");
41+
}
42+
43+
public override void AfterEveryTearDownHook(HookData data)
44+
{
45+
var scope = data.Context.Test.IsSuite ? "OneTimeTearDown" : "TearDown";
46+
TestContext.Progress.WriteLine($"{scope}: {data.HookedMethod?.Name}");
47+
}
48+
}
49+
#endregion
50+
3351
#region Usage
3452
[TestFixture]
3553
[TimeMeasurementHook]

0 commit comments

Comments
 (0)