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)
sleep() method. So the main thread can wait for some time and in the meantime, T1 will resume and complete its execution.
All Java programs have at least one thread, known as the main thread, which is created by the Java Virtual Machine (JVM) at the program's start, when the main() method is invoked.
When a Java program starts up, one thread begins running immediately. This is usually called the main thread of our program because it is the one that is executed when our program begins.
What Is a Thread in Java? A Java thread is the execution path in a program. Everything that runs in Java is run in threads. Every application in the JVM world has threads, at least one, even if you don't call it explicitly. It all starts with the main method of your code, which is run in the main application thread.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With