【问题标题】:initializationError: Test class should have exactly one public zero-argument初始化错误:测试类应该只有一个公共零参数
【发布时间】:2020-05-04 05:22:29
【问题描述】:

我收到初始化错误。

java.lang.Exception: 测试类应该有一个公共的零参数构造函数 我的代码是(这是一个来自 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);
    }
}

任何帮助将不胜感激。

【问题讨论】:

    标签: java junit4


    【解决方案1】:

    错误准确地说明了问题所在。您的类没有“恰好一个公共零参数构造函数”。

    但黄金法则是在商务舱之外进行测试。因此,创建名为public class ComplexTest 的新类并将您的测试方法放在那里。

    【讨论】:

    • 好的。虽然我定义了零参数构造函数并尝试运行测试,但我得到了错误:测试类只能有一个构造函数。但是创建单独的测试类确实有效。 Java 语言中是否内置了黄金法则?
    • 它在技术上不是内置的(如果您的业务类有一个无参数构造函数并且没有其他构造函数它会起作用),但将它分开是非常合理的想法。测试代码在生产中是没有用的,所以你不想让它与生产代码一起编译和打包,这就是为什么你把所有的测试放在单独的测试类中。如果你把它混合在一起,就不可能从发布包中提取测试代码。检查stackoverflow.com/questions/210567/…
    • 这很有道理。非常感谢您的准确回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多