NUnit TestCase with Generics

后端 未结 9 852
梦毁少年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条回答
  •  梦谈多话
    2021-01-31 14:50

    I slightly modified the TestCaseGenericAttribute somebody posted here:

    [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
    public class GenericTestCaseAttribute : TestCaseAttribute, ITestBuilder
    {
        public GenericTestCaseAttribute(params object[] arguments)
            : base(arguments)
        {
        }
    
        IEnumerable 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().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(Type type)
        {
            // arrange
            var sut = new AutoFacMapper();
    
            // act
            sut.RegisterMappings();
            var container = sut.Build();
    
            // assert
            var item = sut.Container.Resolve();
            Assert.AreEqual(type, item.GetType());
        }
    

提交回复
热议问题