NUnit TestCase with Generics

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

    class Sut
    {
        public string ReverseName()
        {
            return new string(typeof(T).Name.Reverse().ToArray());
        }
    }
    
    [TestFixture]
    class TestingGenerics
    {
        public IEnumerable TestCases()
        {
            yield return new Tester { Expectation = "gnirtS"};
            yield return new Tester { Expectation = "23tnI" };
            yield return new Tester> { Expectation = "1`tsiL" };
        }
    
        [TestCaseSource("TestCases")]
        public void TestReverse(ITester tester)
        {
            tester.TestReverse();
        }
    
        public interface ITester
        {
            void TestReverse();
        }
    
        public class Tester : ITester
        {
            private Sut _sut;
    
            public string Expectation { get; set; }
    
            public Tester()
            {
                _sut=new Sut();
            }
    
            public void TestReverse()
            {
                Assert.AreEqual(Expectation,_sut.ReverseName());
            }
    
        }
    }
    

提交回复
热议问题