NUnit SetUp 函数在我的测试之前不是 运行

NUnit SetUp function is not running before my tests

我是 NUnit 的新手,我正在尝试使用 [SetUp] 功能在我的测试之前调用,这样我就可以避免重复。这是我的测试文件的摘录:

using System.Web.Mvc;
using NUnit.Framework;
using ThermostatDotNet.Controllers;



namespace ThermostatTests
{
    [TestFixture]
    public class ThermostatTests
    {
        [SetUp]
        public void Init()
        {
           var thermostat = new ThermostatController();
        }

        [Test]
        public void ReturnsCurrentTemperature()
        {
            thermostat.Reset();
            int actual = thermostat.GetTemp();
            int expected = 20;
            Assert.AreEqual(expected, actual);
        }

然而在测试中,错误显示为 the name thermostat does not exist in the current context - 我是否设置不正确?

谢谢

您需要创建一个字段 thermostat -- 目前它只是您 Init 方法中的一个局部变量。

[TestFixture]
public class ThermostatTests
{
    private ThermostatController thermostat;

    [SetUp]
    public void Init()
    {
       thermostat = new ThermostatController();
    }

    [Test]
    public void ReturnsCurrentTemperature()
    {
        thermostat.Reset();
        int actual = thermostat.GetTemp();
        int expected = 20;
        Assert.AreEqual(expected, actual);
    }
}