I have unit tests for my program and I have to make them all successful
This is one of my unit tests
double x = 5;
double y = 10;
double radius = 20;
Circle target = new Circle(x, y, radius);
Assert.AreEqual(40 * Math.PI, target.Circumference, 0.01, "Circumference is false");
target.Radius = 0;
Assert.AreEqual(0, target.Circumference, 0.01, "Circumference is at a radius of 0 0");
target.Radius = -10;
Assert.AreEqual(0, target.Circumference, 0.01, "Circumference is at a negativ radius null");
The first test is successful but the next isn't. My problem is how do I change Circumfernece when only the radius is changing?
Here is my Circle class
public class Circle
{
public double X { get; set; }
public double Y { get; set; }
public double Radius { get; set; }
public double Circumference{ get;}
public Circle(double x, double y, double radius)
{
X = x;
Y = y;
if (radius < 0)
{
Radius = 0;
Circumference = 0;
}
else
{
Radius = radius;
Circumference = radius * 2 * Math.PI;
}
}
//...
}
CodePudding user response:
It is much better to move all the logic and validation from constructor to the properties.
This way your code will not be broken, if somebody assigns or changes Radius
directly.
Try this
public class Circle
{
private double _radius;
public double X { get; set; }
public double Y { get; set; }
public double Radius
{
get {return _radius;}
set
{
if (value <= 0) _radius = 0;
else _radius=value;
}
}
public double Circumference
{
get { return _radius * 2 * Math.PI };
}
public Circle(double x, double y, double radius)
{
X = x;
Y = y;
Radius = radius;
}
}