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

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; try { BeforeTest(context); context.CurrentResult = innerCommand.Execute(context); } catch (Exception ex) { if (ex is ThreadAbortException) Thread.ResetAbort(); context.CurrentResult.RecordException(ex); } finally { if (context.ExecutionStatus != TestExecutionStatus.AbortRequested) AfterTest(context); } return context.CurrentResult; } } }