由于设计不良,单元测试有时会失败

时间:2017-01-28 13:48:18

标签: c# unit-testing mstest

以下是传感器和指示器这两个类,它包含一些业务逻辑和单元测试。由于设计不良,单元测试有时会失败。我试图修复实现并更正单元测试,但我仍然遇到问题。我需要你的帮助来解决实施问题。

public class Sensor
{
    const double Offset = 16;

    public double GetFuelAmountValue()
    {
        double value;
        SampleAmount(out value);

        return Offset + value;
    }

    private static void SampleAmount(out double fuelTelemetryValue)
    {
        Random basicRandomNumbersGenerator = new Random();
        fuelTelemetryValue = basicRandomNumbersGenerator.Next(0, 25);
    }
}

public class Indicator
{
    private const double LowFuelTreshold = 7;
    private const double HighFuelTreshold = 21;

    Sensor _sensor = new Sensor();

    bool _alarm = false;
    private long _alarmCount = 0;


    public void Check()
    {
        double LitersOfFuelValue = _sensor.GetFuelAmountValue();

        if (LitersOfFuelValue < LowFuelTreshold || HighFuelTreshold < LitersOfFuelValue)
        {
            _alarm = true;
            _alarmCount += 1;
        }
    }

    public bool Alarm
    {
        get { return _alarm; }
    }

}

这是测试

[TestClass]
public class FuelIndicatorTest
{
    [TestMethod]
    public void Foo()
    {
        Indicator indicator = new Indicator();
        indicator.Check();
        Assert.AreEqual(false, indicator.Alarm);
    }
}

1 个答案:

答案 0 :(得分:1)

我知道这是一个简化的代码 - 而不是生产代码。这里有一种方法可以模拟随机生成的数字FuelTelementryNumber并通过构造函数在测试中传递它。

public class Sensor
{
    const double Offset = 16;
    Func<double> _getFuelTelemetry;

    public Sensor(Func<double> getFuelTelemetry)
    {
        _getFuelTelemetry = getFuelTelemetry;
    }

    public Sensor()
        : this(SampleAmount)
    {
    }

    public double GetFuelAmountValue()
    {
        double value = _getFuelTelemetry();
        return Offset + value;
    }

    private static double SampleAmount()
    {
        Random basicRandomNumbersGenerator = new Random();
        return basicRandomNumbersGenerator.Next(0, 25);
    }
}


public class Indicator
{
    private const double LowFuelTreshold = 7;
    private const double HighFuelTreshold = 21;

    Sensor _sensor;

    public Indicator(Sensor sensor)
    {
        _sensor = sensor;
    }

    public Indicator() : this(new Sensor())
    {
    }

    bool _alarm = false;
    private long _alarmCount = 0;


    public void Check()
    {
        double LitersOfFuelValue = _sensor.GetFuelAmountValue();

        if (LitersOfFuelValue < LowFuelTreshold || HighFuelTreshold < LitersOfFuelValue)
        {
            _alarm = true;
            _alarmCount += 1;
        }
    }

    public bool Alarm
    {
        get { return _alarm; }
    }

}

[TestClass]
public class FuelIndicatorTest
{
    [TestMethod]
    public void Foo()
    {
        Indicator indicator = new Indicator(new Sensor(() => {return 25;}));
        indicator.Check();
        Assert.AreEqual(true, indicator.Alarm);
    }
}
相关问题