为每个测试夹具定义相同的设置和拆卸

Define the same setup and teardown for every test fixture

我有一个包含多个 TestFixture 的项目,我想为每个测试定义相同的 [SetUp] [TearDown] 方法。考虑到我有很多 TestFixture,我想避免编辑所有文件来添加这两条指令。

浏览 nunit 文档我认为 [SetUpFixture] 是完美的解决方案。 所以我复制了 example 并尝试 运行 它,但似乎我的 TearDown 方法从未被 运行ned 而 SetUp 正在按我预期的方式执行。为了断言这一点,我只是使用了 throw 语句。

我的问题是:

  1. 我的用例有误吗?我应该做不同的事情来实现我的目标吗?
  2. 我是否错误地使用了 SetUpFixture 属性?

下面是我的 SetUpFixture class。我正在使用 Nunit 3.11。

using System;
using NUnit.Framework;

namespace MyTestProject
{
  [SetUpFixture]
  public class MySetUpClass
  {
    [OneTimeSetUp]
    public void RunBeforeAnyTests()
    {
      StaticClass.Init();
//    throw new InvalidOperationException("SetUp reached");
    }

    [OneTimeTearDown]
    public void RunAfterAnyTests()
    {
      StaticClass.Finalize();
//    throw new InvalidOperationException("TearDown reached");
    }
  }
}
  1. 您的用例很好,您可以通过定义 class 并定义 [Setup] 和 [Teardown] 来实现。如果您继承它们,则每次测试它们将 运行 一次。它记录在 https://github.com/nunit/docs/wiki/SetUp-and-TearDown.

  2. 帮助对我来说似乎不太清楚,你对结果的解释也不清楚,但我建议在你的 StaticClass 调用之前尝试一些断点或记录,以确保它们不是干扰你的行为。

我创建了示例程序来根据患者的血压水平预测健康状况,并实施了示例单元测试(NUnit 测试)。为了更好地理解,我已经使用 [SetUp][Tear Down] 对每种测试方法实施了示例单元测试。

主要class:


     public class HealthReport
    {
        public string Healthdamage(int pressure)
        {
            if (pressure == 120)
            {
                return "normal";
            }
            if (pressure > 120 && pressure < 140)
            {
                return "At risk";
            }
            if (pressure > 140)
            {
                return "Highly risk";
            }
            else
            {
                return "low BP";
            }
        }
    }

单元测试class:

    [TestFixture]
    public class Healthtest
    {
        private HealthReport health;
        [SetUp]
        public void SetUp()
        {
            health = new HealthReport();
        }
        [TearDown]
        public void Teardown()
        {
            health = null;
        }

        [Test]
        public void Health_Damage_returnnormal()
        {
            string statusreport = health.Healthdamage(120);
            Assert.That(statusreport, Is.EqualTo("normal"));
        }
        [Test]
        public void Health_Damage_returnAtrisk()
        {
            string statusreport = health.Healthdamage(130);
            Assert.That(statusreport, Is.EqualTo("At risk"));
        }
        [Test]
        public void Health_Damage_returnHighlyrisk()
        {
            string statusreport = health.Healthdamage(180);
            Assert.That(statusreport, Is.EqualTo("Highly risk"));
        }
        [Test]
        public void Health_Damage_returnlow()
        {
            string statusreport = health.Healthdamage(110);
            Assert.That(statusreport, Is.EqualTo("low BP"));
        }