NUnit TestCase with Generics

后端 未结 9 853
梦毁少年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:46

    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 : ITestRunner
    {
        public void RunTest(object _param, T _expectedValue)
        {
            T result = MakeGenericCall();
    
            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);
    }
    

提交回复
热议问题