Java 使用assert语句测试方法

Java 使用assert语句测试方法,java,assert,Java,Assert,因此,我对两个子类CheckingAccount和SavingAccount都有一个equals方法,我还有一个名为BankAccount的超类。我对如何使用assert语句测试equals方法感到困惑?非常感谢 下面是equals方法的代码 核对 public boolean equals(Object object) { if (this == object) return true; if (object == null) return fa

因此,我对两个子类
CheckingAccount
SavingAccount
都有一个
equals
方法,我还有一个名为
BankAccount
的超类。我对如何使用assert语句测试
equals
方法感到困惑?非常感谢

下面是
equals
方法的代码 核对

public boolean equals(Object object) {
    if (this == object)
        return true;
    if (object == null)
        return false;
    if (getClass() != object.getClass())
        return false;
    CheckingAcc other = (CheckingAcc) object;
    if (accountNumber != other.accountNumber)
        return false;
    return true;
}
在萨文加奇

public boolean equals(Object object) {
    if (this == object)
        return true;
    if (object == null)
        return false;
    if (getClass() != object.getClass())
        return false;
    SavingAcc other = (SavingAcc) object;
    if (accountNumber != other.accountNumber)
        return false;
    return true;
}

通常,您会编写一个单元测试程序来创建一些对象,设置它们,并使用断言来验证您期望为真的条件。当断言失败时,程序将向您发出警报

因此,在您的测试程序中,您可以,例如:

CheckingAccount test = new CheckingAccount(1);
CheckingAccount other = new CheckingAccount(2);

SavingAccount anotherTest = new SavingAccount();
SavingAccount anotherOther = new SavingAccount();
anotherTest.accountNumber = 3;
anotherOther.accountNumber = 3;

assert !test.equals(other); // this should evaluate to true, passing the assertion
assert anotherTest.equals(anotherOther); // this should evaluate to true, passing the assertion
看起来您使用帐号作为帐户相等的手段,因此我假设在创建这些对象时,您要么将帐号作为构造函数的参数传递,要么显式分配它

显然,这是一个非常贫乏的示例,但我不确定对象的创建/结构。但只要你掌握了要点,这可以扩展到提供更有意义的测试

编辑为了全面测试equals方法,您可以设置断言,以便它们都应计算为true(并通过),以及测试equals方法的所有功能(完整代码覆盖率)


仅供参考,您可以将每个方法的最后三行替换为“return accountNumber==other.accountNumber;”。我建议您阅读JUnit4教程,例如:
CheckingAccount newTest = new CheckingAccount(1);
CheckingAccount secondTest = new CheckingAccount(1);
SavingAccount newOther = new SavingAccount(3);

assert newTest.equals(newTest); // test first if
assert !newTest.equals(null); // test second if
assert !newTest.equals(newOther) // test third if
assert newTest.equals(secondTest); // test fourth if