Search code examples
javahttp-headersjunit5equalshashcode

Why are 2 org.apache.hc.core5.http.Header not equal when created with the same content?


Why does

import org.apache.hc.core5.http.Header;

Assertions.assertEquals(new BasicHeader("name", "value", true), new BasicHeader("name", "value", true));

or

Assertions.assertEquals(new BasicHeader("name", "value", false), new BasicHeader("name", "value", false));

fail the assertion?

It probably has somethin to do with different hashcodes being generated, but I fail to see - if it should be the reason - why it is like it is.


Solution

  • The BasicHeader class does not override the equals method, so it uses the default implementation of the equals method from the Object class.

    The default implementation of the equals method checks if two objects are the same instance, meaning that they have the same memory address.

    Instead you can make assertion element by element, example:

    BasicHeader header1 = new BasicHeader("name", "value", true);
    BasicHeader header2 = new BasicHeader("name", "value", true);
    
    assertEquals(header1.getName(), header2.getName());
    assertEquals(header1.getValue(), header2.getValue());
    assertEquals(header1.isSensitive(), header2.isSensitive());
    

    Note: there are other ways.