How to Test Time In Java

We all know we should have unit tests for most of our Java code. But how do you test your functionalities that are depending on time?

You don’t because it is too difficult? You test it manually, changing the actual time of your computer? Or did you check StackOverflow and read that you need to replace all your System.currentTimeMillis() calls to a custom implementation? Java 8 introduced java.time.Clock for this purpose, but what if you have a big legacy application and it is infeasible to introduce yourOwnCurrentTimeMillis?

Enter the TimeTransformer. A small open source utility using bytecode weaving to rewire all calls to System.currentTimeMillis(). It provides an API to completely alter the time of a JVM, making time travel in your applications and unit tests possible. This presentation demonstrates the TimeTransformer on a small webserver where I want to verify that given I am locked out after too many incorrect password attempts, when the lock-out-time has elapsed, then I can log in again.

Video producer: http://www.devoxx.com/

Related Videos:

Tags: