首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用assert语句测试方法

使用assert语句测试方法
EN

Stack Overflow用户
提问于 2014-03-27 03:28:24
回答 1查看 110关注 0票数 0

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

下面是equals方法在CheckingAcc中的代码

代码语言:javascript
运行
复制
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中

代码语言:javascript
运行
复制
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;
}
EN

Stack Overflow用户

回答已采纳

发布于 2014-03-27 03:34:15

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

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

代码语言:javascript
运行
复制
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),以及测试等于方法的所有功能(完整的代码覆盖率)。

代码语言:javascript
运行
复制
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
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22677689

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档