This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Engineering » Testing
Bookmark "test with dependency on current date" Watch "test with dependency on current date" New topic
Author

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)


TIA


java amateur
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30138
    
150

Miguel,
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.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, 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
author
Sheriff

Joined: Jan 23, 2002
Posts: 11962
    
    5
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: http://aspose.com/file-tools
 
subject: test with dependency on current date
 
Similar Threads
Silly Date Problem
response.setHeader not working
Request Object
Regex reluctant mode problem
Loop/Array Logic