xUnit理论测试使用泛型

Ayb*_*btu 13 c# generics attributes xunit

在xUnit中,我可以Theory使用以下形式的泛型:

[Theory]
[MemberData(SomeScenario)]
public void TestMethod<T>(T myType)
{
    Assert.Equal(typeof(double), typeof(T));
}

public static IEnumerable<object[]> SomeScenario()
{
    yield return new object[] { 1.23D };
}
Run Code Online (Sandbox Code Playgroud)

这将给我通用T参数as double.是否可以使用MemberData为具有以下签名的测试指定泛型类型参数:

[Theory]
[MemberData(SomeTypeScenario)]
public void TestMethod<T>()
{
    Assert.Equal(typeof(double), typeof(T));
}
Run Code Online (Sandbox Code Playgroud)

如果无法使用MemberData或任何其他提供的属性(我怀疑它不是),是否可以为Xunit创建一个可以实现此目的的属性?也许类似于在Scenarios方法中指定类型并使用与Jon Skeet的答案类似的方式使用反射:C#中的泛型,使用变量的类型作为参数

Ond*_*dar 10

您可以简单地将其包含Type为输入参数.例如:

[Theory]
[MemberData(SomeTypeScenario)]
public void TestMethod(Type type) {
  Assert.Equal(typeof(double), type);
}

public static IEnumerable<object[]> SomeScenario() {
  yield return new object[] { typeof(double) };
}
Run Code Online (Sandbox Code Playgroud)

没有必要在xunit上使用泛型.

编辑(如果你真的需要泛型)

1)您需要继承子类ITestMethod以保持通用方法信息,它还必须实现IXunitSerializable

// assuming namespace Contosco
public class GenericTestMethod : MarshalByRefObject, ITestMethod, IXunitSerializable
{
    public IMethodInfo Method { get; set; }
    public ITestClass TestClass { get; set; }
    public ITypeInfo GenericArgument { get; set; }

    /// <summary />
    [Obsolete("Called by the de-serializer; should only be called by deriving classes for de-serialization purposes")]
    public GenericTestMethod()
    {
    }

    public GenericTestMethod(ITestClass @class, IMethodInfo method, ITypeInfo genericArgument)
    {
        this.Method = method;
        this.TestClass = @class;
        this.GenericArgument = genericArgument;
    }

    public void Serialize(IXunitSerializationInfo info)
    {
        info.AddValue("MethodName", (object) this.Method.Name, (Type) null);
        info.AddValue("TestClass", (object) this.TestClass, (Type) null);
        info.AddValue("GenericArgumentAssemblyName", GenericArgument.Assembly.Name);
        info.AddValue("GenericArgumentTypeName", GenericArgument.Name);
    }

    public static Type GetType(string assemblyName, string typeName)
    {
#if XUNIT_FRAMEWORK    // This behavior is only for v2, and only done on the remote app domain side
        if (assemblyName.EndsWith(ExecutionHelper.SubstitutionToken, StringComparison.OrdinalIgnoreCase))
            assemblyName = assemblyName.Substring(0, assemblyName.Length - ExecutionHelper.SubstitutionToken.Length + 1) + ExecutionHelper.PlatformSuffix;
#endif

#if NET35 || NET452
        // Support both long name ("assembly, version=x.x.x.x, etc.") and short name ("assembly")
        var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assemblyName || a.GetName().Name == assemblyName);
        if (assembly == null)
        {
            try
            {
                assembly = Assembly.Load(assemblyName);
            }
            catch { }
        }
#else
        System.Reflection.Assembly assembly = null;
        try
        {
            // Make sure we only use the short form
            var an = new AssemblyName(assemblyName);
            assembly = System.Reflection.Assembly.Load(new AssemblyName { Name = an.Name, Version = an.Version });

        }
        catch { }
#endif

        if (assembly == null)
            return null;

        return assembly.GetType(typeName);
    }

    public void Deserialize(IXunitSerializationInfo info)
    {
        this.TestClass = info.GetValue<ITestClass>("TestClass");
        string assemblyName = info.GetValue<string>("GenericArgumentAssemblyName");
        string typeName = info.GetValue<string>("GenericArgumentTypeName");
        this.GenericArgument = Reflector.Wrap(GetType(assemblyName, typeName));
        this.Method = this.TestClass.Class.GetMethod(info.GetValue<string>("MethodName"), true).MakeGenericMethod(GenericArgument);
    }
}
Run Code Online (Sandbox Code Playgroud)

2)你需要为泛型方法编写自己的发现者,它必须是子类 IXunitTestCaseDiscoverer

// assuming namespace Contosco
public class GenericMethodDiscoverer : IXunitTestCaseDiscoverer
{
    public GenericMethodDiscoverer(IMessageSink diagnosticMessageSink)
    {
        DiagnosticMessageSink = diagnosticMessageSink;
    }

    protected IMessageSink DiagnosticMessageSink { get; }

    public IEnumerable<IXunitTestCase> Discover(ITestFrameworkDiscoveryOptions discoveryOptions,
        ITestMethod testMethod, IAttributeInfo factAttribute)
    {
        var result = new List<IXunitTestCase>();
        var types = factAttribute.GetNamedArgument<Type[]>("Types");
        foreach (var type in types)
        {
            var typeInfo = new ReflectionTypeInfo(type);
            var genericMethodInfo = testMethod.Method.MakeGenericMethod(typeInfo);
            var genericTestMethod = new GenericTestMethod(testMethod.TestClass, genericMethodInfo, typeInfo);

            result.Add(
                new XunitTestCase(DiagnosticMessageSink, discoveryOptions.MethodDisplayOrDefault(),
                    genericTestMethod));
        }

        return result;
    }
}
Run Code Online (Sandbox Code Playgroud)

3)最后,您可以为通用方法创建属性,并通过XunitTestCaseDiscoverer属性将其挂钩到自定义发现者

// assuming namespace Contosco
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
[XunitTestCaseDiscoverer("Contosco.GenericMethodDiscoverer", "Contosco")]
public sealed class GenericMethodAttribute : FactAttribute
{
    public Type[] Types { get; private set; }

    public GenericMethodAttribute(Type[] types)
    {
        Types = types;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

[GenericMethod(new Type[] { typeof(double), typeof(int) })]
public void TestGeneric<T>()
{
  Assert.Equal(typeof(T), typeof(double));
}
Run Code Online (Sandbox Code Playgroud)

  • 我在问题中给出的例子是一个简单的案例.如果我想测试一个只带有泛型参数的泛型方法,例如:`public int MyMethod <T>(string someInput)`,该怎么办?我可以使用反射调用此方法传入`Type`,但这会变得混乱. (2认同)
  • 我收到消息:System.InvalidOperationException:无法对 ContainsGenericParameters 为 true 的类型或方法执行后期绑定操作。堆栈跟踪: RuntimeMethodInfo.ThrowNoInvokeException() RuntimeMethodInfo.InvokeArgumentsCheck(对象 obj,BindingFlags invokeAttr,活页夹活页夹,Object[] 参数,CultureInfo 区域性) RuntimeMethodInfo.Invoke(对象 obj,BindingFlags invokeAttr,活页夹活页夹,Object[] 参数,CultureInfo 区域性) MethodBase.Invoke(Object obj, Object[] 参数) (2认同)