NUnit TestCase with Generics

后端 未结 9 856
梦毁少年i
梦毁少年i 2021-01-31 13:53

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

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

<         


        
9条回答
  •  旧时难觅i
    2021-01-31 14:55

    You can make custom GenericTestCaseAttribute

    [Test]
    [GenericTestCase(typeof(MyClass) ,"Some response", TestName = "Test1")]
    [GenericTestCase(typeof(MyClass1) ,"Some response", TestName = "Test2")]
    public void MapWithInitTest(string expectedResponse)
    {
        // Arrange
    
        // Act
        var response = MyClassUnderTest.MyMethod();
    
        // Assert
        Assert.AreEqual(expectedResponse, response);
    }
    

    Here is implementation of 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 ITestBuilder.BuildFrom(IMethodInfo method, Test suite)
        {
            if (method.IsGenericMethodDefinition && _type != null)
            {
                var gm = method.MakeGenericMethod(_type);
                return BuildFrom(gm, suite);
            }
            return BuildFrom(method, suite);
        }
    }
    

提交回复
热议问题