Nunit测试设置方法带参数

25

我们可以使用带参数的测试设置方法吗?我需要为每个fixture中的测试提供不同的设置。

我们是否有类似于假设想法的东西(或类似的方式):

[SetUp]
[Argument("value-1")]
[Argument("value-2")]
[Argument("value-3")]
public void InitializeTest(string value)
{
    //set env var with value
}

1
不清楚为什么你要尝试对“设置”进行参数化,而不是对“测试”进行参数化。 - Jon Skeet
1
设置完成后,测试将执行相同的工作。将此部分纳入测试并使测试参数化可能更有意义! - dushyantp
3个回答

47

可以使用带参数的TestFixture属性来完成。

如果类中所有的测试都依赖于相同的参数,则应该使用此方法。

该类需要一个构造函数,构造函数中需要传递与TestFixture属性相同的参数。

请参见https://github.com/nunit/docs/wiki/TestFixture-Attribute上的参数化测试夹具。

[TestFixture("Oscar")]
[TestFixture("Paul")]
[TestFixture("Peter")]
public class NameTest
{
    private string _name;

    public NameTest(string name)
    {
        _name = name;
    }

    [Test]
    public void Test_something_that_depends_on_name()
    {
        //Todo...
    }

    [Test]
    public void Test_something_that_also_depends_on_name()
    {
        //Todo...
    }
    //...
}

这段代码来自于nunit文档网站:

[TestFixture("hello", "hello", "goodbye")]
[TestFixture("zip", "zip")]
[TestFixture(42, 42, 99)]
public class ParameterizedTestFixture
{
    private readonly string eq1;
    private readonly string eq2;
    private readonly string neq;

    public ParameterizedTestFixture(string eq1, string eq2, string neq)
    {
        this.eq1 = eq1;
        this.eq2 = eq2;
        this.neq = neq;
    }

    public ParameterizedTestFixture(string eq1, string eq2)
        : this(eq1, eq2, null)
    {
    }

    public ParameterizedTestFixture(int eq1, int eq2, int neq)
    {
        this.eq1 = eq1.ToString();
        this.eq2 = eq2.ToString();
        this.neq = neq.ToString();
    }

    [Test]
    public void TestEquality()
    {
        Assert.AreEqual(eq1, eq2);
        if (eq1 != null && eq2 != null)
            Assert.AreEqual(eq1.GetHashCode(), eq2.GetHashCode());
    }

    [Test]
    public void TestInequality()
    {
        Assert.AreNotEqual(eq1, neq);
        if (eq1 != null && neq != null)
            Assert.AreNotEqual(eq1.GetHashCode(), neq.GetHashCode());
    }
}

24

SetUp每次执行一次测试,对于一个测试只有一个SetUp和TearDown。您可以从测试中显式地调用初始化方法,然后使用TestCase属性创建数据驱动测试。

public void InitializeTest(string value)
{
    //set env var with value
}

[TestCase("Value-1")]
[TestCase("Value-2")]
[TestCase("Value-3")]
public void Test(string value)
{
    InitializeTest(value);

    //Arange
    //Act
    //Assert
}

因此,您将拥有三个测试,每个测试都会调用InitializeTest并使用不同的参数。

1

设置方法用于执行一些预测试工作,包括为测试准备所需的任何值,例如在设置方法中设置这些值而不是提供参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接