使用assert语句来测试方法

时间:2014-03-27 03:28:24

标签: java assert

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

以下是equals方法的代码 在CheckingAcc

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;
}

在SavingAcc中

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;
}

1 个答案:

答案 0 :(得分:0)

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

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

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方法的所有功能(完成)代码覆盖率)

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
相关问题