Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.setLenient(false);
    present.set(year, month - 1, day, 0, 0);

    today = dformat.format(present.getTime());
    System.out.println(today);
}

Here is my test:

@Test 
public void currentDay()
{
    Date current = new Date();
    System.out.println(current);
    assertEquals("today:", current, new Date());
}

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

comp.work.wk.Date@d3ade7

Any help would be appreciated.

like image 361
user3276602 Avatar asked Feb 05 '14 18:02

user3276602


People also ask

How do I compare two dates in Junit?

You simply use Date. compareTo() to compare two date objects.

How do I compare two date objects in Java?

In Java, two dates can be compared using the compareTo() method of Comparable interface. This method returns '0' if both the dates are equal, it returns a value "greater than 0" if date1 is after date2 and it returns a value "less than 0" if date1 is before date2.


2 Answers

Overriding default equals method is not necessary. You simply use Date.compareTo() to compare two date objects.

like image 152
Karthik Kota Avatar answered Sep 30 '22 06:09

Karthik Kota


Although the answer by @Shrikanth solves it, this issue also arises with normal Date objects. Two possible solutions are given here:

  1. Make use of DateUtils.truncate (or even DateUtils.truncatedEquals) to compare the dates. This is something you could use in your equals method, or for normal Date objects directly in you assertEquals/assertTrue.

    assertEquals(DateUtils.truncate(date1,Calendar.SECOND), 
                 DateUtils.truncate(date2,Calendar.SECOND));
    
  2. Don't check whether the dates are the same, but whether they are close enough to eachother (for JUnit test sake):

    assertTrue("Dates aren't close enough to each other!", 
               Math.abs(date2.getTime() - date1.getTime()) < 1000);
    
like image 20
Hans Wouters Avatar answered Sep 30 '22 07:09

Hans Wouters