0

I am getting initializatoinError.

java.lang.Exception: Test class should have exactly one public zero-argument constructor My code is (This is an example from Java Programming Interview Exposed):

import org.junit.*;

import static org.junit.Assert.*;

public class Complex {
    private final double real;
    private final double imaginary;

    public Complex(final double r, final double i) {
        this.real = r;
        this.imaginary = i;
    }
    public Complex add(final Complex other) {
        return new Complex(this.real + other.real,
                this.imaginary + other.imaginary);
    }
    // hashCode omitted for brevity
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Complex complex = (Complex) o;
        if (Double.compare(complex.imaginary, imaginary) != 0) return false;
        if (Double.compare(complex.real, real) != 0) return false;
        return true;
    }

    @Test
    public void complexNumberAddition() {
        final Complex expected = new Complex(6,2);
        final Complex a = new Complex(8,0);
        final Complex b = new Complex(-2,2);
        assertEquals(a.add(b), expected);
    }
}

Any help would be appreciated.

1 Answers1

1

The error says exactly what is wrong. Your class doesn't have "exactly one public zero-argument constructor".

But the gold rule is to have tests outside of business classes. So create new class called public class ComplexTest and put your test method there.

bambula
  • 365
  • 1
  • 12
  • Ok. Though I define zero argument constructor and try to run the test, I get the error: Test class can only have one constructor. Creating separate test class does work though. Is the gold rule built into Java language? – Vishwajit Bhadrashetty Jan 18 '20 at 11:43
  • It's not technically built in (if your business class had one no-arg constructor and no other constructors it would work), but it's very reasonable idea to have it separated. The test code is useless in production, so you don't want to have it compiled and packed together with production code, that's why you put all your tests into separated test classes. If you had it mixed together it would be impossible to extract the test code from release bundle. Check https://stackoverflow.com/questions/210567/package-structure-for-a-java-project – bambula Jan 21 '20 at 18:12
  • That makes sense bambula. Thanks a lot for your precise answers. – Vishwajit Bhadrashetty Jan 23 '20 at 08:01