File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Testing and the fly likes test with dependency on current date Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Engineering » Testing
Bookmark "test with dependency on current date" Watch "test with dependency on current date" New topic

test with dependency on current date

miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
this is more of an academic Q since i could set date far from today (by then i want to have this app finished )

inspired here and here i wrote my own testAgeOfPerson method.

Then a Q arised: in a few weeks my test shall fail, since then will assertFalse:

How can i turn this around?

BTW i guess that in both links one should use (i know i do)


java amateur
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33132

The easiest way is to provide a new signature that lets you pass in two dates. For example:

The signature adds some functionality to the class too. It allows you to calculate someone's age on a certain date. There isn't much that can go wrong in calculateAge(Date). You could always test that by having someone born today and making sure they are 0.

The meat of the logic is in calculateAgeOnGivenDate(Date, Date). This method is more testable.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
what an excelent idea you had: now i can have the best of both worlds (today or any day and trusty testing too)

Thanks a lot!
Lasse Koskela

Joined: Jan 23, 2002
Posts: 11962
I tend to add a layer between the application and the system clock and then mock the system clock for tests that depend on the current date.

In other words, I use classes/methods such as:
Time.millis() instead of System.currentTimeMillis()
Time.setTimeSource(TimeSource s) for replacing the real TimeSource with a fake
Time.resetTimeSource() for reverting back to the real TimeSource

Author of Test Driven (2007) and Effective Unit Testing (2013) [Blog] [HowToAskQuestionsOnJavaRanch]
I agree. Here's the link:
subject: test with dependency on current date
It's not a secret anymore!