Categories: Java, Unit Tests

Mocking the current date-time (properly) with Java

fixed current date-time

fixed date-timeIt’s not unusual to face situations where we need to capture the current system’s date-time in order to calculate some future date, make validations and so on. The problem generally appears as soon as we need to check whether some calculated date was correctly generated or not. When we directly use the instruction “new Date()” to retrieve the current system’s date-time it’s hard to mock it afterwards. I’ve seen people using many approaches to get the mocked current date-time and it’s possible to assure that the majority of them is not elegant neither simple.

You can look at some approaches here:
http://stackoverflow.com/questions/11887799/how-to-mock-new-date-in-java-using-mockito

Now I will present you a simple code example that uses the “new Date()” and it’s definitely NOT easy to test.

And then the unit test class:

If you check the above test class, you will notice that we don’t have a way to validate both start and end date-times returned by the class under test. This is to say that even if you get the current date-time in the test and then calculate the expected start and end date-times, you won’t be able to compare it with the actual date-times (returned from the class under test). The reason is simple: your test class and the class under test would capture the current date-time in different moments, so they would never have exactly the same millisecond, consequently the comparison would always fail.

The proper way to ensure good assertions in these scenarios is to mock the current date-time so we can have predefined date-times to compare with.

Let’s see how a simple modification in the way we capture the current date-time can make our life much easier in the unit tests later on. Just one thing that is important to mention: my code suggestion will make use of the “joda-time” library.

Using the above approach we can now easily define a fixed current date-time during the test execution.

In the last code snippet were combined the “before” and “after” methods to respectively define a fixed date-time before the test run and reset it to the system’s default after the test execution. It makes things much easier for the following test assertions.

Article info