Manage current time in unit testing?

Is there a way to manipulate the current time in a jUnit 4.5 test? I have the following method that I would like to have unit test for

public String getLastWeek() { GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("Europe/Stockholm")); c.setFirstDayOfWeek(GregorianCalendar.MONDAY); c.add(GregorianCalendar.WEEK_OF_YEAR, -1); return c.get(GregorianCalendar.YEAR) + " " + c.get(GregorianCalendar.WEEK_OF_YEAR); } 

One way to simplify testing is to break it into two methods.

 public String getLastWeek() { GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("Europe/Stockholm")); return getLastWeekFor(c); } public String getLastWeekFor(GregorianCalander c) { c.setFirstDayOfWeek(GregorianCalendar.MONDAY); c.add(GregorianCalendar.WEEK_OF_YEAR, -1); return c.get(GregorianCalendar.YEAR) + " " + c.get(GregorianCalendar.WEEK_OF_YEAR); } 

This allows me to check the week subtraction logic, but leaves getLastWeek untested, and I prefer to have only one method for this.

+6
java time junit
source share
3 answers

You have no real way to manage your system time.

Actually, you reorganized the method pretty nicely to make it verifiable. I would keep it at the same time.

+6
source share

Here I see two ways.

Create a DateUtils factory class that encapsulates the construction of Calendar and Date instances. Then you can change it to a managed factory. Ie, you have a second DateUtils implementation that also provides the setCurrentTime method, and then explicitly returns the Calendar instances set for that date.

Or you can use JMockit to actually β€œoverride” your call to new GregorianCalendar , an mock instance is returned instead. I did not do this myself, but there is a description here .

Your option, splitting the method into two methods, is also a perfectly valid option. I think this is what most people, including myself, do, but it actually harms your design, especially if the class is exposed to different code.

+3
source share

Looks like you're trying to recreate what JODA Time is. I will bring it if you do not know. You can compromise between rethinking the wheel and adding a dependency.

+1
source share

All Articles