【问题标题】:Nunit test setup method with argument带参数的 Nunit 测试设置方法
【发布时间】:2013-04-29 10:22:58
【问题描述】:

我们可以有一个带参数的测试设置方法吗? 我需要为夹具中的每个测试设置不同的设置。

我们有什么(或类似的方式)作为假设的想法:

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

【问题讨论】:

标签: c# unit-testing nunit


【解决方案1】:

可以使用带有参数的 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());
    }
}

【讨论】:

    【解决方案2】:

    Setup 每个测试执行一次,对于一个测试只有一个 SetUp 和 TearDown。您可以从测试中显式调用 Initialize 方法,然后使用 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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-08-25
        • 2013-08-28
        • 2011-05-10
        • 2021-10-28
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 2011-10-30
        相关资源
        最近更新 更多