Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic JUnit of date check

Tags:

java

date

junit

I ma trying to write a Junit for the following code;

/**
 * Check if a date is greater than 24 hours
 * @param dateToCheck the date to check
 * @return true if it is greater than otherwise false
 */
public static boolean dateGreaterThan24Hours(Date dateToCheck){
    if(dateToCheck == null){
        throw new IllegalArgumentException("The date passed to check for greater than 24 hours is null");
    }
    long millisIn24Hours = 1000 * 60 * 60 * 24;
    Date hours24ago = new Date(new Date().getTime() - millisIn24Hours);
    if (dateToCheck.before(hours24ago)) {
        //24 hrs have passed
        return true;
    }
    return false;
}

However I am struggling to do so because the method only accepts a date to check against. Meaning y current attempt at a test method is clearly going to fail;

@Test
public void checkLessThan24HoursShouldReturnTrue(){
    //Calendar represents the 7th of July 2014 at 17.30pm
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2014);
    cal.set(Calendar.MONTH, 07);
    cal.set(Calendar.DAY_OF_MONTH, 7);
    cal.set(Calendar.HOUR_OF_DAY,17);
    cal.set(Calendar.MINUTE,30);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);

    Date july7 = cal.getTime();

    //Calendar represents the 6th of July 2014 at 18.30pm
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2014);
    cal.set(Calendar.MONTH, 07);
    cal.set(Calendar.DAY_OF_MONTH, 6);
    cal.set(Calendar.HOUR_OF_DAY,18);
    cal.set(Calendar.MINUTE,30);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);

    Date july6 = cal.getTime();
}

Can anyone suggest how i can refactor the original method to make it easier to test?

Thanks

like image 560
Biscuit128 Avatar asked Jul 17 '14 13:07

Biscuit128


1 Answers

You don't have to change the original method. The easiest tests to write would be:

@Test
public void checkMoreThan24HoursShouldReturnTrue() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -25);
    assertTrue(YourClass.dateGreaterThan24Hours(cal.getTime()));
}

@Test
public void checkLessThan24HoursShouldReturnFalse() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.HOUR_OF_DAY, -23);
    assertFalse(YourClass.dateGreaterThan24Hours(cal.getTime()));
}

Also I would recommend some refactorings as suggested by @DaveNewton in the comments, and a test that verifies your custom exception for null argument.

like image 189
Keppil Avatar answered Sep 28 '22 17:09

Keppil