NUnit:如何 运行 对多个对象进行测试 class - 比 TestCaseSourceAttribute 更好的选择?

NUnit: How to run a test class on multiple objects - better alternative than TestCaseSourceAttribute?

我想用同一个测试测试接口的所有实现 class。我已经知道 TestCaseSourceAttribute,因此我将其设置为从静态 testObjects 数组加载对象实例。此代码按我的意愿工作:

[TestFixture]
public class MySerializerTests
{
    // IStreamSerializers loaded by the TestCaseSource attribute.
    static object[] testObjects = new object[]
    {
        new BinarySerializer(),
        new XmlSerializer(),
        new JsonSerializer()
    };

    [Test, TestCaseSource("testObjects")]
    public void Serialize_NullStreamArgument_ThrowsArgumentException(IStreamSerializer serializer)
    {
        Map map = new Map();
        Assert.Throws<ArgumentNullException>(() => serializer.Serialize(null, map));
    }
}

但是,我必须在每个方法上使用 [TestCaseSource("testObjects")],这使得我拥有的方法数量相当繁琐。有没有一种方法可以将 TextCaseSource 属性替换为适用于整个测试 class 的属性?也许类似于参数化 FestFixture 的工作方式?

我想要类似的东西,但是我可以通过测试的构造函数传递我测试的 classes 的实例 class:

[TestFixture(0)]
[TestFixture(1)]
[TestFixture(2)]
public class MySerializerTests
{
    // IStreamSerializers loaded by the TestCaseSource attribute.
    static object[] testObjects = new object[]
    {
        new BinarySerializer(),
        new XmlSerializer(),
        new JsonSerializer()
    };

    int currentIndex;

    public MySerializerTests(int index)
    {
        currentIndex = 0;
    }

    [Test]
    public void Serialize_NullStreamArgument_ThrowsArgumentException()
    {
        Map map = new Map();

        Assert.Throws<ArgumentNullException>(() => testObjects[currentIndex].Serialize(null, map));
    }
}

您需要 TestFixtureSourceAttribute。

[TestFixtureSource("testObjects")]
public class MySerializerTests
{
    // IStreamSerializers loaded by the TestCaseSource attribute.
    static IStreamSerializer[] testObjects = new IStreamSerializer[]
    {
        new BinarySerializer(),
        new XmlSerializer(),
        new JsonSerializer()
    };

    IStreamSerializer _serializer;

    public MySerializerTests(IStreamSerializer serializer)
    {
        _serializer = serializer;
    }

    [Test]
    public void Serialize_NullStreamArgument_ThrowsArgumentException()
    {
        Map map = new Map();
        Assert.Throws<ArgumentNullException>(
            () => _serializer.Serialize(null, map));
    }
}

我没有编译这个,所以你可能需要修正拼写错误等