Skip to content

Comparing dates with JUnit testing

Hello I’m new to the site and have a issue with my application using JUnit testing. My issue is when I try to compare the Date method with itself it always fails. I printed the Date object in the test to see the problem and always end up with the package name and random letters. Here is the Date constructor:

public class Date
SimpleDateFormat dformat = new SimpleDateFormat("dd-MM-yyyy");

private int day;
private int month;
private int year;

public Date() 
    String today;
    Calendar present = Calendar.getInstance();

    day = present.get(Calendar.DAY_OF_MONTH);
    month = present.get(Calendar.MONTH);
    year = present.get(Calendar.YEAR);

    present.set(year, month - 1, day, 0, 0);

    today = dformat.format(present.getTime());

Here is my test:

public void currentDay()
    Date current = new Date();
    assertEquals("today:", current, new Date());

Yet the result always fails and I get something on the lines of:

Any help would be appreciated.



The default equals object compares memory locations. If both objects are pointing to same memory location then only it will print equals which is not the case in your program. since they are pointing to two different memory locations it is always giving false which is expected.

If you feel your assertEquals(date1,date2) method should return true since the contents are equal then you should override the equals method. And when ever you override equals you should override hashcode() method also to ensure that you can confidently use your class instance as a key in any hashing based collection like HashMap or HashSet.

Here is a link explaining how to override equals() and hashcode() method

And don’t name your class same as any API class as Jon Skeet suggested.

Hope this helps.

User contributions licensed under: CC BY-SA
5 People found this is helpful