56

有没有办法使用 TestCase 将泛型类型传递给 NUnit 中的测试?

这是我想做的,但语法不正确......

[Test]
[TestCase<IMyInterface, MyConcreteClass>]
public void MyMethod_GenericCall_MakesGenericCall<TInterface, TConcreteClass>()
{
    // Arrange

    // Act
    var response = MyClassUnderTest.MyMethod<TInterface>();

    // Assert
    Assert.IsInstanceOf<TConcreteClass>(response);
}

或者如果不是,实现相同功能的最佳方法是什么(显然我将在真实代码中有多个 TestCases)?

用另一个例子更新......

这是另一个传递了单个泛型类型的示例...

[Test]
[TestCase<MyClass>("Some response")]
public void MyMethod_GenericCall_MakesGenericCall<T>(string expectedResponse)
{
    // Arrange

    // Act
    var response = MyClassUnderTest.MyMethod<T>();

    // Assert
    Assert.AreEqual(expectedResponse, response);
}
4

9 回答 9

81

只要可以从参数中推断出泛型类型参数,NUnit 测试方法实际上可以是泛型的:

[TestCase(42)]
[TestCase("string")]
[TestCase(double.Epsilon)]
public void GenericTest<T>(T instance)
{
    Console.WriteLine(instance);
}

NUnit 通用测试

如果无法推断出泛型参数,则测试运行程序将不知道如何解析类型参数:

[TestCase(42)]
[TestCase("string")]
[TestCase(double.Epsilon)]
public void GenericTest<T>(object instance)
{
    Console.WriteLine(instance);
}

NUnit 通用测试失败

但在这种情况下,您可以实现自定义属性:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestCaseGenericAttribute : TestCaseAttribute, ITestBuilder
{
    public TestCaseGenericAttribute(params object[] arguments)
        : base(arguments)
    {
    }

    public Type[] TypeArguments { get; set; }

    IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
    {
        if (!method.IsGenericMethodDefinition)
            return base.BuildFrom(method, suite);

        if (TypeArguments == null || TypeArguments.Length != method.GetGenericArguments().Length)
        {
            var parms = new TestCaseParameters { RunState = RunState.NotRunnable };
            parms.Properties.Set("_SKIPREASON", $"{nameof(TypeArguments)} should have {method.GetGenericArguments().Length} elements");
            return new[] { new NUnitTestCaseBuilder().BuildTestMethod(method, suite, parms) };
        }

        var genMethod = method.MakeGenericMethod(TypeArguments);
        return base.BuildFrom(genMethod, suite);
    }
}

用法:

[TestCaseGeneric("Some response", TypeArguments = new[] { typeof(IMyInterface), typeof(MyConcreteClass) }]
public void MyMethod_GenericCall_MakesGenericCall<T1, T2>(string expectedResponse)
{
    // whatever
}

以及类似的定制TestCaseSourceAttribute

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class TestCaseSourceGenericAttribute : TestCaseSourceAttribute, ITestBuilder
{
    public TestCaseSourceGenericAttribute(string sourceName)
        : base(sourceName)
    {
    }

    public Type[] TypeArguments { get; set; }

    IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
    {
        if (!method.IsGenericMethodDefinition)
            return base.BuildFrom(method, suite);

        if (TypeArguments == null || TypeArguments.Length != method.GetGenericArguments().Length)
        {
            var parms = new TestCaseParameters { RunState = RunState.NotRunnable };
            parms.Properties.Set("_SKIPREASON", $"{nameof(TypeArguments)} should have {method.GetGenericArguments().Length} elements");
            return new[] { new NUnitTestCaseBuilder().BuildTestMethod(method, suite, parms) };
        }

        var genMethod = method.MakeGenericMethod(TypeArguments);
        return base.BuildFrom(genMethod, suite);
    }
}

用法:

[TestCaseSourceGeneric(nameof(mySource)), TypeArguments = new[] { typeof(IMyInterface), typeof(MyConcreteClass) }]
于 2017-04-11T07:57:17.043 回答
25

我今天有机会做类似的事情,并且对使用反射不满意。

我决定利用 [TestCaseSource] 代替,将测试逻辑作为测试上下文委托给通用测试类,固定在非通用接口上,并从单个测试中调用接口(我的真实测试在接口中有更多方法,并使用 AutoFixture 设置上下文):

class Sut<T>
{
    public string ReverseName()
    {
        return new string(typeof(T).Name.Reverse().ToArray());
    }
}

[TestFixture]
class TestingGenerics
{
    public static IEnumerable<ITester> TestCases()
    {
        yield return new Tester<string> { Expectation = "gnirtS"};
        yield return new Tester<int> { Expectation = "23tnI" };
        yield return new Tester<List<string>> { Expectation = "1`tsiL" };
    }

    [TestCaseSource("TestCases")]
    public void TestReverse(ITester tester)
    {
        tester.TestReverse();
    }

    public interface ITester
    {
        void TestReverse();
    }

    public class Tester<T> : ITester
    {
        private Sut<T> _sut;

        public string Expectation { get; set; }

        public Tester()
        {
            _sut=new Sut<T>();
        }

        public void TestReverse()
        {
            Assert.AreEqual(Expectation,_sut.ReverseName());
        }

    }
}
于 2013-05-31T20:32:31.150 回答
10

您可以制作自定义 GenericTestCaseAttribute

[Test]
[GenericTestCase(typeof(MyClass) ,"Some response", TestName = "Test1")]
[GenericTestCase(typeof(MyClass1) ,"Some response", TestName = "Test2")]
public void MapWithInitTest<T>(string expectedResponse)
{
    // Arrange

    // Act
    var response = MyClassUnderTest.MyMethod<T>();

    // Assert
    Assert.AreEqual(expectedResponse, response);
}

这是 GenericTestCaseAttribute 的实现

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
{
    private readonly Type _type;
    public GenericTestCaseAttribute(Type type, params object[] arguments) : base(arguments)
    {
        _type = type;
    }

    IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
    {
        if (method.IsGenericMethodDefinition && _type != null)
        {
            var gm = method.MakeGenericMethod(_type);
            return BuildFrom(gm, suite);
        }
        return BuildFrom(method, suite);
    }
}
于 2016-11-15T20:46:03.523 回答
7

首先从测试开始——即使是在测试时。你想让我做什么?大概是这样的:

[Test]
public void Test_GenericCalls()
{
    MyMethod_GenericCall_MakesGenericCall<int>("an int response");
    MyMethod_GenericCall_MakesGenericCall<string>("a string response");
      :
}

然后你可以让你的测试成为一个普通的旧功能测试。没有 [测试] 标记。

public void MyMethod_GenericCall_MakesGenericCall<T>(string expectedResponse)
{
    // Arrange

    // Act
    var response = MyClassUnderTest.MyMethod<T>();

    // Assert
    Assert.AreEqual(expectedResponse, response);
}
于 2010-03-02T19:10:22.807 回答
7

C# 中的属性不能是通用的,因此您将无法完全按照您的意愿做事。也许最简单的事情是将TestCase属性放在使用反射调用真实方法的辅助方法上。像这样的东西可能会起作用(注意,未经测试):

    [TestCase(typeof(MyClass), "SomeResponse")]
    public void TestWrapper(Type t, string s)
    {
        typeof(MyClassUnderTest).GetMethod("MyMethod_GenericCall_MakesGenericCall").MakeGenericMethod(t).Invoke(null, new [] { s });
    }
于 2010-03-02T19:13:16.610 回答
4

我上周做了类似的事情。这就是我最终得到的结果:

internal interface ITestRunner
{
    void RunTest(object _param, object _expectedValue);
}

internal class TestRunner<T> : ITestRunner
{
    public void RunTest(object _param, T _expectedValue)
    {
        T result = MakeGenericCall<T>();

        Assert.AreEqual(_expectedValue, result);
    }
    public void RunTest(object _param, object _expectedValue)
    {
        RunTest(_param, (T)_expectedValue);
    }
}

然后是测试本身:

[Test]
[TestCase(typeof(int), "my param", 20)]
[TestCase(typeof(double), "my param", 123.456789)]
public void TestParse(Type _type, object _param, object _expectedValue)
{
    Type runnerType = typeof(TestRunner<>);
    var runner = Activator.CreateInstance(runnerType.MakeGenericType(_type));
    ((ITestRunner)runner).RunTest(_param, _expectedValue);
}
于 2010-03-02T19:17:19.500 回答
2

可能使用返回对象的通用函数进行测试?例子:

public Empleado TestObjetoEmpleado(Empleado objEmpleado) 
{
    return objEmpleado; 
}

谢谢

于 2010-12-06T18:50:01.033 回答
2

我稍微修改了某人在此处发布的 TestCaseGenericAttribute:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
{
    public GenericTestCaseAttribute(params object[] arguments)
        : base(arguments)
    {
    }

    IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
    {
        if (!method.IsGenericMethodDefinition) return base.BuildFrom(method, suite);
        var numberOfGenericArguments = method.GetGenericArguments().Length;
        var typeArguments = Arguments.Take(numberOfGenericArguments).OfType<Type>().ToArray();

        if (typeArguments.Length != numberOfGenericArguments)
        {
            var parms = new TestCaseParameters { RunState = RunState.NotRunnable };
            parms.Properties.Set("_SKIPREASON", $"Arguments should have {typeArguments} type elements");
            return new[] { new NUnitTestCaseBuilder().BuildTestMethod(method, suite, parms) };
        }

        var genMethod = method.MakeGenericMethod(typeArguments);
        return new TestCaseAttribute(Arguments.Skip(numberOfGenericArguments).ToArray()).BuildFrom(genMethod, suite);
    }
}

这个版本需要一个所有参数的列表,从类型参数开始,从类型参数开始。用法:

    [Test]
    [GenericTestCase(typeof(IMailService), typeof(MailService))]
    [GenericTestCase(typeof(ILogger), typeof(Logger))]
    public void ValidateResolution<TQuery>(Type type)
    {
        // arrange
        var sut = new AutoFacMapper();

        // act
        sut.RegisterMappings();
        var container = sut.Build();

        // assert
        var item = sut.Container.Resolve<TQuery>();
        Assert.AreEqual(type, item.GetType());
    }
于 2018-09-28T14:47:23.240 回答
0

我已经写了我自己的TestCaseGenericAttributeTestCaseGenericSourceAttribute. https://github.com/nunit/nunit/issues/3580

于 2020-06-09T15:46:12.793 回答