<PackageReference Include="NUnit" Version="3.11.0" />

BeforeAndAfterTestCommand

TestActionCommand handles a single ITestAction applied to a test. It runs the BeforeTest method, then runs the test and finally runs the AfterTest method.
using System; using System.Threading; namespace NUnit.Framework.Internal.Commands { public abstract class BeforeAndAfterTestCommand : DelegatingTestCommand { protected Action<TestExecutionContext> BeforeTest; protected Action<TestExecutionContext> AfterTest; public BeforeAndAfterTestCommand(TestCommand innerCommand) : base(innerCommand) { } public override TestResult Execute(TestExecutionContext context) { Guard.OperationValid(BeforeTest != null, "BeforeTest was not set by the derived class constructor"); Guard.OperationValid(AfterTest != null, "AfterTest was not set by the derived class constructor"); if (base.Test.Fixture == null) base.Test.Fixture = context.TestObject; RunTestMethodInThreadAbortSafeZone(context, delegate { BeforeTest(context); context.CurrentResult = innerCommand.Execute(context); }); if (context.ExecutionStatus != TestExecutionStatus.AbortRequested) RunTestMethodInThreadAbortSafeZone(context, delegate { AfterTest(context); }); return context.CurrentResult; } private static void RunTestMethodInThreadAbortSafeZone(TestExecutionContext context, Action action) { try { action(); } catch (Exception ex) { if (ex is ThreadAbortException) Thread.ResetAbort(); context.CurrentResult.RecordException(ex); } } } }