Below are the two classes Sensor and Indicator which contains some business logic and a Unit Test. The unit test fails sometimes due to a bad design. I tried to fix the implementation and correct the unit test but I am still getting problem. I need your help to fix the implementation.
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; }
}
}
This is the test
[TestClass]
public class FuelIndicatorTest
{
[TestMethod]
public void Foo()
{
Indicator indicator = new Indicator();
indicator.Check();
Assert.AreEqual(false, indicator.Alarm);
}
}
I understand that this is a simplified code - not production one. Here one way how to mock random generated number FuelTelementryNumber
and pass it in test via constructor.
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.