Test method returning N days before today

I'm a bit confused, I have a method which returns date N day before today, However I do not now how to test it:

public String getBeforeDay(int noDays){

    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH,-noDays);

    DateFormat dateFormat  = new SimpleDateFormat("yyyy-MM-dd");
    Date date = calendar.getTime();

    return dateFormat.format(date);
}

@Test
public void testGetBeforeDay(){
    assertEquals("2014-04-02", dateService.getBeforeDay(10));
}

and as string in the assertEquals is hardcoded, tommorow test will not pass. What is a good practise to solve such test?

Jon Skeet
people
quotationmark

What is a good practise to solve such test?

The problem is that you're depending on something ephemeral: the current date/time.

The fix I prefer for this is to introduce the idea of a Clock as a dependency (to be handled as with any other dependency) which can tell you the current time. For example:

public interface Clock {
    Date now();
}

You can then have one implementation which uses the system clock, and a fake to be used for testing. In your getBeforeDay method, you'd initialize the Calendar using:

calendar.setTime(clock.now());

I've used this approach very successfully in various projects, and the java.time package in Java 8 comes with it baked in. (If you can possibly use java.time instead of java.util.*, do so!)

people

See more on this question at Stackoverflow