带有泛型的NUnit TestCase [英] NUnit TestCase with Generics

查看:131
本文介绍了带有泛型的NUnit TestCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用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);
}

或者,如果不是,实现相同功能的最佳方法是什么(显然,我将在真实代码中拥有多个TestCases)?

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

使用另一个示例进行更新...

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

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

推荐答案

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

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

我决定利用[TestCaseSource]代替,将测试逻辑作为测试上下文委派给通用测试类,固定在非通用接口上,并从各个测试中调用该接口(我的实际测试中还有更多方法界面,然后使用AutoFixture设置上下文):

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

    }
}

这篇关于带有泛型的NUnit TestCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆