在NUnit TestFixture构造函数中使用Values-和Range-Attribute

Xar*_*ugh 2 c# nunit parameterized-unit-test nunit-2.6

我有多种测试方法,应该测试多个参数的所有可能组合.我可以在这样的方法上使用NUnit ValueAttributeRangeAttribute:

[TestFixture]
public class MyExampleTests
{
    [Test]
    public void TestedEntity_GivenParemeter_Passes(
        [Values(1, 2)] int inputA,
        [Range(1, 4)] int inputB)
    {
        if (inputA > 0 && inputB > 0)
            Assert.Pass();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,在我的实际案例中,有4个参数,十几个方法和更多的值,因此写出每个方法的所有值变得冗长乏味,如果我想进行更改,我可能会在某处犯错.

如何将所有值组合的测试生成从各个方法移到TestFixture体中?以下不起作用,但它将是我想要的:

[TestFixture]
public class MyExampleTests2
{
    readonly int inputA;
    readonly int inputB;

    public MyExampleTests2(
        [Values(1, 2)] int inputA,
        [Range(1, 4)] int inputB)
    {
        this.inputA = inputA;
        this.inputB = inputB;
    }

    [Test]
    public void TestedEntity_GivenParemeter_Passes()
    {
        if (this.inputA > 0 && this.inputB > 0)
            Assert.Pass();
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经知道TestFixtureAttribute可以获取参数,但它们不能按我想要的方式工作.我只能给每个参数一个硬编码值.相反,我想使用范围,并让NUnit为每个组合创建一个测试.此外,我希望该解决方案适用于NUnit 2.6.4.

Jon*_*eet 11

你可以使用ValuesSource:

[Test]
public void TestedEntity_GivenParemeter_Passes(
    [ValueSource(nameof(FirstSource))] int inputA,
    [ValueSource(nameof(SecondSource))] int inputB)
{
    if (inputA > 0 && inputB > 0)
        Assert.Pass();
}

private static readonly int[] FirstSource = { 1, 2 };
private static readonly IEnumerable<int> SecondSource = Enumerable.Range(1, 4);
Run Code Online (Sandbox Code Playgroud)

如果要避免重复参数声明,可以创建包含InputA和的属性的单个类型InputB,以及返回该类型序列的源.