views:

49

answers:

4

I want to test some class methods that contain logic dependent on the current time it is running. I'd like to set the thread/jvm/system time to a specific future date in the JUnit setup and run my tests. Also I would like this to be temporary. Has anyone done this before?

I was thinking of something similar to TimeZone.setDefault(timezone)

A: 

I don't believe there's a way of doing this using java.util.Date.

If you are using joda-time then you can. See this

Mike Q
+2  A: 

I have been struggling with this too. The best solution I found so far is having a TimeHelper class which manages the time stuff : as a Date factory, keeping DateFormatters and so on so that these things are not distributed over the codebase.

With Easymock, or another mock framework, it is then straightforward to test time related stuff.

Peter Tillemans
A: 

You're going about this the wrong way. Your class methods should be accepting a long value which represents the time - they should not be accepting a TimeZone. If you refactor your methods to be decoupled from the fact that they receive there 'time' from a TimeZone, then you can easily test your methods without having to do what you're trying to do now; you simply call your methods with pre-defined long values representative of a particular time, rather then calling them with a TimeZone object whose default value is something predetermined that you wish to test.

You need to decouple the methods which receive a 'time' parameter from the source which provides that time value. By doing this, you can run your code while using TimeZone or the current system time, and you can test your code while using predefined time values that you wish to test.

Go ahead and try refactoring your code and see if you can achieve the desired capabilities - you should be able to. Come back with any further questions and we'll be glad to help!

Good luck.

Shakedown
+2  A: 

You could use AspectJ and wrap methods around java.lang.System.currentTimeMillis(), java.util.Date.new() and java.util.Calendar.getInstance() which adjust the time according to your needs.

tob
+1 I got to try this some time.
Peter Tillemans