因此,我为两个子类CheckingAccount和SavingAccount提供了一个CheckingAccount方法,还有一个名为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;
}发布于 2014-03-27 03:34:15
通常,您会编写一个单元测试程序来创建一些对象,设置它们,并使用断言来验证您期望为真的条件。当断言失败时,程序将通知您。
因此,在您的测试程序中,可以这样做,例如:
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看起来您使用帐户号作为帐户相等的一种方式,所以我假设在创建这些对象时,您可以将帐号作为构造函数的参数传递,或者显式地分配它。
显然,这是一个非常小的例子,但我不确定您的对象的创建/结构。但是这可以扩展到提供更有意义的测试,只要你得到了要点。
编辑以便全面测试您的等号方法,您可以设置断言,以便它们都可以计算为true (和pass),以及测试等于方法的所有功能(完整的代码覆盖率)。
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 ifhttps://stackoverflow.com/questions/22677689
复制相似问题