Write a test:
public void testAddComplexWithDecimalPoints() {
Complex z1 = new Complex(1.5, 2.0);
Complex z2 = new Complex(2.1, 2.5);
Complex z3 = z1.add(z2);
assertEquals(3.6, z3.getRealPart(), 0.000001);
assertEquals(4.5, z3.getImaginaryPart(), 0.0000001);
}
Repair the code:
private double real;
private double imaginary;
public Complex(double real, double imaginary) {
this.real = real;
this.imaginary = imaginary;
}
public Complex add(Complex z) {
return new Complex(this.real+z.real, this.imaginary + z.imaginary);
}
public double getRealPart() {
return this.real;
}
public double getImaginaryPart() {
return this.imaginary;
}
Repair the test code:
private double tolerance = 0.000001;
public void testAdd() {
Complex z1 = new Complex(1, 1);
Complex z2 = new Complex(1, 1);
Complex z3 = z1.add(z2);
assertEquals(2, z3.getRealPart(), tolerance);
assertEquals(2, z3.getImaginaryPart(), tolerance);
}
public void testAddNonEqualNumbers() {
Complex z1 = new Complex(1, 1);
Complex z2 = new Complex(2, 2);
Complex z3 = z1.add(z2);
assertEquals(3, z3.getRealPart(), tolerance);
assertEquals(3, z3.getImaginaryPart(), tolerance);
}
public void testAddComplexWithDecimalPoints() {
Complex z1 = new Complex(1.5, 2.0);
Complex z2 = new Complex(2.1, 2.5);
Complex z3 = z1.add(z2);
assertEquals(3.6, z3.getRealPart(), tolerance);
assertEquals(4.5, z3.getImaginaryPart(), tolerance);
}
Run the test
Repeat