Fireburn
Fireburn

Reputation: 1021

JUnit not calling object equals when testing

JUnit is throwing this error:

java.lang.AssertionError: expected:<com.mycompany.models.EntityStringProperty@1e81f4dc> but was:<com.mycompany.models.EntityStringProperty@4d591d15>
    at org.junit.Assert.fail(Assert.java:88)
    at org.junit.Assert.failNotEquals(Assert.java:834)
    at org.junit.Assert.assertEquals(Assert.java:118)
    at org.junit.Assert.assertEquals(Assert.java:144)
    at com.mycompany.models.EntityPropertyTest.testStringEntity(EntityPropertyTest.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

For this test:

  @Test
  public void testStringEntity() {
    EntityProperty stringProperty = new EntityStringProperty("hello world");
    EntityProperty stringPropertyCompare = new EntityStringProperty("hello world");
    assertEquals(stringProperty, stringPropertyCompare);
  }

Even the equals had been overridden:

public class EntityStringProperty extends PrimitiveEntityProperty { 
  /* NOTE: PrimitiveEntityProperty implements EntityProperty */
  public EntityStringProperty(String stringValue) {
    super(stringValue, String.class);
  }

  @Override public boolean equals(Object obj) {
    if (EntityStringProperty.class.isAssignableFrom(obj.getClass())) {
      EntityStringProperty property = (EntityStringProperty) obj;
      if (getStringValue().equals(property.getStringValue()) && getValueType().isAssignableFrom(
          property.getClass())) {
        return true;
      }
    }
    return false;
  }
}

What could be wrong here? How can I make this test for the equals for the two object correctly?

Upvotes: 0

Views: 209

Answers (1)

quarks
quarks

Reputation: 35282

Here's how to fix this, change the implemenation of equals to this:

  @Override public boolean equals(Object obj) {
    if (EntityStringProperty.class.isAssignableFrom(obj.getClass())) {
      EntityStringProperty property = (EntityStringProperty) obj;
      if (getStringValue().equals(property.getStringValue()) && getValueType().isAssignableFrom(
          property.getValueType())) {
        return true;
      }
    }
    return false;
  }

Notice the change,

getValueType().isAssignableFrom(property.getValueType())

Upvotes: 2

Related Questions