Question

So i have an equals method for both subclasses CheckingAccount and SavingAccount and i also have a superclass named BankAccount. I am confusing at how to test the equals method using assert statement? Thanks very much.

Here is the code for equals method In 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;
}

In 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;
}
Was it helpful?

Solution

Typically, you'd write a unit test program that creates some objects, sets them up, and use asserts to verify conditions that you are expecting to be true. The program will alert you when an assertion fails.

So in your test program you could, for example:

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

It looks like you use an account number as a means of equality for your accounts, so I'm assuming when creating these objects, you either pass the account number as a parameter for the constructor, or assign it explicitly

Obviously this is a very meager example, but I'm not sure about the creation/structure of your objects. But this could be extended to provide more meaningful testing, as long as you get the gist.

EDIT so to fully test your equals method, you can set up your assertions so that they all should evaluate to true (and pass) as well as testing all the functionality of your equals method (complete code coverage)

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top