测试之前,NUnit SetUp函数未运行

时间:2019-09-06 16:27:30

标签: c# nunit

我是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-我是否设置错误?

谢谢

1 个答案:

答案 0 :(得分:3)

您需要将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);
    }
}