我希望能够模拟任意测试的失败,以检查我的TearDown逻辑是否正常工作。如果您愿意,可以对单元测试进行单元测试。
但实际上,我在TearDown中使用了一些可以在故障时产生附件的装置。我必须能够展示这个功能,但是当你最需要它时很难产生故障。
所以,我想创建一个测试参数,指定我希望失败的测试的名称。现在,我可以轻松编写实现IWrapTestMethod
或IApplyToContext
的属性,但是我需要在每个测试方法上应用它。
有没有办法在不触及每个测试和/或夹具的情况下实现它?通过在每次测试之前运行的某种程序集级别属性或程序集级别设置方法?
至关重要的是,这种逻辑不会阻止TearDown
方法运行,所以ITestAction
从BeforeTest
抛出一个例外不适合该法案。
可以这样做吗?
我找到了解决方案:
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using System;
using System.Reflection;
[assembly: Common.EnableFailureSimulation]
namespace Common
{
public class SimulateFailureMethodInfoWrapper : IMethodInfo
{
private readonly IMethodInfo m_mi;
public SimulateFailureMethodInfoWrapper(IMethodInfo mi)
{
m_mi = mi;
}
public ITypeInfo TypeInfo => m_mi.TypeInfo;
public MethodInfo MethodInfo => m_mi.MethodInfo;
public string Name => m_mi.Name;
public bool IsAbstract => m_mi.IsAbstract;
public bool IsPublic => m_mi.IsPublic;
public bool ContainsGenericParameters => m_mi.ContainsGenericParameters;
public bool IsGenericMethod => m_mi.IsGenericMethod;
public bool IsGenericMethodDefinition => m_mi.IsGenericMethodDefinition;
public ITypeInfo ReturnType => m_mi.ReturnType;
public T[] GetCustomAttributes<T>(bool inherit) where T : class => m_mi.GetCustomAttributes<T>(inherit);
public Type[] GetGenericArguments() => m_mi.GetGenericArguments();
public IParameterInfo[] GetParameters() => m_mi.GetParameters();
public object Invoke(object fixture, params object[] args)
{
var res = m_mi.Invoke(fixture, args);
Assert.Fail("Failure simulation");
return res;
}
public bool IsDefined<T>(bool inherit) where T : class => m_mi.IsDefined<T>(inherit);
public IMethodInfo MakeGenericMethod(params Type[] typeArguments) => m_mi.MakeGenericMethod(typeArguments);
}
[AttributeUsage(AttributeTargets.Assembly)]
public class EnableFailureSimulationAttribute : Attribute, ITestAction
{
private static string s_failTestMethod = GetParameterByName("!");
public ActionTargets Targets => ActionTargets.Test;
public void AfterTest(ITest test)
{
}
public void BeforeTest(ITest test)
{
if (test.MethodName == s_failTestMethod && test is Test testImpl)
{
testImpl.Method = new SimulateFailureMethodInfoWrapper(testImpl.Method);
s_failTestMethod = "!";
}
}
}
}
另一种方法是使用Moq
并模拟IMethodInfo
界面而不是真正的SimulateFailureMethodInfoWrapper
类。
无论如何,这似乎完美无缺。