0

I have a class for a string-number pair. This class has the method compareTo implemented.

A method of another class returns a collection of elements of the pair type.

I wanted to perform a unit test on this method, and therefore wrote the following:

@Test
public void testWeight() {

    Collection<StringNumber<BigDecimal>> expected = new Vector<StringNumber<BigDecimal>>();
    expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
    expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));

    Collection<StringNumber<BigDecimal>> actual = new Vector<StringNumber<BigDecimal>>();
    expected.add(new StringNumber<BigDecimal>("a", BigDecimal.ONE));
    expected.add(new StringNumber<BigDecimal>("b", BigDecimal.ONE));

    //Collection<StringNumber<BigDecimal>> actual = A.f();

    assertEquals(expected, actual);
}

But as you can see, the assertion fails, even though the elements in the collections are identical. What can be the reason?

The error I get is

java.lang.AssertionError: expected: java.util.Vector<[a:1, b:1]> but was: java.util.Vector<[a:1, b:1]>

Which does not make scene to me.

Artium
  • 5,147
  • 8
  • 39
  • 60

1 Answers1

1

Your StringNumber class requires equals() method. Then it will work. Assuming this class contains string and number fields (auto-generated by my IDE):

@Override
public boolean equals(Object o) {
    if (this == o) {
        return true;
    }
    if (!(o instanceof StringNumber)) {
        return false;
    }
    StringNumber that = (StringNumber) o;
    if (number != null ? !number.equals(that.number) : that.number != null) {
        return false;
    }
    return !(string != null ? !string.equals(that.string) : that.string != null);

}

@Override
public int hashCode() {
    int result = string != null ? string.hashCode() : 0;
    result = 31 * result + (number != null ? number.hashCode() : 0);
    return result;
}

Few remarks:

  • Two Vector's (why are you using such archaic data structure) are equal if:

both [...] have the same size, and all corresponding pairs of elements in the two lists are equal. (Two elements e1 and e2 are equal if (e1==null ? e2==null : e1.equals(e2)).)

That's why overriding equals() is required.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674