-2

How would I go about writing a test case for this equals method that compares ID numbers after it checks if an object is an "Integer" or "Patron".

Here is the method:

public boolean equals(Object other) {
   
      boolean bool = false;
      
      if (other instanceof Patron) {
         Patron patron = (Patron) other;
         bool = this.idNumber == patron.idNumber;
      } else if (other instanceof Integer) {
         Integer id = (Integer) other;
         bool = this.idNumber == id;
      }
      return bool;
  • 1
    You would create various instances of the class and then assert `obj1.equals(obj2)` is true or false, depending on the value you expect. Note your handling of `Integer` breaks the associativity contract of `equals` because `patron.equals(integer)` will not always equal `integer.equals(patron)`. – Slaw Dec 03 '21 at 22:18
  • 1
    Generally speaking, things of different classes should not be considered equal. – user16632363 Dec 03 '21 at 22:25
  • Write the test just like for any other method. Call the method under test with some value, and compare the returned value to what you expect. `equals` is no different than any other method here. – Robert Dec 09 '21 at 17:35

1 Answers1

1

If you want to verify whether the contract for the equals and hashCode methods is met, I would suggest using EqualsVerifier.

If you don't want to use an external library, I would suggest taking a look at it to get an idea of what (and why) you need to test. It is a great source to learn about equals and hashCode.

It's very simple to write a test:

EqualsVerifier.forClass(Foo.class).verify();

There's also a less strict alternative:

EqualsVerifier.simple()
            .forClass(Foo.class).verify();

It also has several options to suppress other warnings.

Oboe
  • 2,643
  • 2
  • 9
  • 17