SetUpTearDownItem
SetUpTearDownItem holds the setup and teardown methods
for a single level of the inheritance hierarchy.
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal.Builders;
using NUnit.Framework.Internal.Execution;
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace NUnit.Framework.Internal.Commands
{
[NullableContext(1)]
[Nullable(0)]
public class SetUpTearDownItem
{
[Nullable(2)]
private readonly IMethodValidator _methodValidator;
private readonly IList<IMethodInfo> _setUpMethods;
private readonly IList<IMethodInfo> _tearDownMethods;
private bool _setUpWasRun;
public bool HasMethods {
get {
if (_setUpMethods.Count <= 0)
return _tearDownMethods.Count > 0;
return true;
}
}
public SetUpTearDownItem(IList<IMethodInfo> setUpMethods, IList<IMethodInfo> tearDownMethods, [Nullable(2)] IMethodValidator methodValidator = null)
{
_setUpMethods = setUpMethods;
_tearDownMethods = tearDownMethods;
_methodValidator = methodValidator;
}
public void RunSetUp(TestExecutionContext context)
{
_setUpWasRun = true;
foreach (IMethodInfo setUpMethod in _setUpMethods) {
RunSetUpOrTearDownMethod(context, setUpMethod);
}
}
public void RunTearDown(TestExecutionContext context)
{
if (_setUpWasRun)
try {
int count = context.CurrentResult.AssertionResults.Count;
int num = _tearDownMethods.Count;
while (--num >= 0) {
RunSetUpOrTearDownMethod(context, _tearDownMethods[num]);
}
if (context.CurrentResult.AssertionResults.Count > count)
context.CurrentResult.RecordTestCompletion();
} catch (Exception ex) {
context.CurrentResult.RecordTearDownException(ex);
}
}
private void RunSetUpOrTearDownMethod(TestExecutionContext context, IMethodInfo method)
{
Guard.ArgumentNotAsyncVoid(method.MethodInfo, "method");
_methodValidator?.Validate(method.MethodInfo);
MethodInfoCache.TestMethodMetadata testMethodMetadata = MethodInfoCache.Get(method);
if (testMethodMetadata.IsAsyncOperation)
AsyncToSyncAdapter.Await(context, () => InvokeMethod(method, context));
else
InvokeMethod(method, context);
}
private static object InvokeMethod(IMethodInfo method, TestExecutionContext context)
{
return method.Invoke(method.IsStatic ? null : context.TestObject, null);
}
}
}