C# 带有泛型的 NUnit 测试用例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2364929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:45:59  来源:igfitidea点击:

NUnit TestCase with Generics

c#unit-testinggenericsnunittestcase

提问by Russell Giddings

Is there any way to pass generic types using a TestCase to a test in NUnit?

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

This is what I would like to do but the syntax is not correct...

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

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

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

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

Or if not, what is the best way to achieve the same functionality (obviously I'll have multiple TestCases in the real code)?

或者,如果没有,实现相同功能的最佳方法是什么(显然我将在实际代码中使用多个测试用例)?

Update with another example...

更新另一个例子...

Here is another example with a single generic type passed...

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

[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);
}

采纳答案by IanBru

I had occasion to do something similar today, and wasn't happy with using reflection.

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

I decided to leverage [TestCaseSource] instead by delegating the test logic as a test context to a generic testing class, pinned on a non-generic interface, and called the interface from individual tests (my real tests have many more methods in the interface, and use AutoFixture to set up the context):

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

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

[TestFixture]
class TestingGenerics
{
    public 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());
        }

    }
}

回答by Ray

Start with the test first--even when testing. What do you want to do? Probably something like this:

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

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

Then you can just make your test a plain old function test. No [Test] marker.

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

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

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

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

回答by kvb

Attributes in C# cannot be generic, so you won't be able to do things exactly as you'd like. Perhaps the easiest thing would be to put TestCaseattributes onto a helper method which uses reflection to call the real method. Something like this might work (note, untested):

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 });
    }

回答by Adam Lear

I did something similar last week. Here's what I ended up with:

我上周做了类似的事情。这是我的结果:

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);
    }
}

And then the test itself:

然后是测试本身:

[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);
}

回答by Pedro Balda

As might be testing with generic functions that return objects?. Example:

可能正在使用返回对象的泛型函数进行测试?。例子:

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

Thanks

谢谢

回答by R.Titov

You can make custom GenericTestCaseAttribute

您可以自定义 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);
}

Here is implementation of GenericTestCaseAttribute

这是 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);
    }
}

回答by Gy?rgy K?szeg

NUnit test methods actually can be generic as long as the generic type arguments can be inferred from parameters:

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

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

NUnit Generic Test

NUnit 通用测试

If the generic arguments cannot be inferred, the test runner will not have a clue how to resolve type arguments:

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

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

NUnit Generic Test Fail

NUnit 通用测试失败

But in this case you can implement a custom attribute:

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

[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);
    }
}

Usage:

用法:

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

And a similar customization for TestCaseSourceAttribute:

以及类似的定制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);
    }
}

Usage:

用法:

[TestCaseSourceGeneric(nameof(mySource)), TypeArguments = new[] { typeof(IMyInterface), typeof(MyConcreteClass) }]

回答by realbart

I slightly modified the TestCaseGenericAttribute somebody posted here:

我稍微修改了某人在这里发布的 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);
    }
}

This version expects one list of all parameters, starting with the type parameters, starting with the type paramters. Usage:

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

    [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());
    }