• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

test with dependency on current date

 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34669
366
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
miguel lisboa
Ranch Hand
Posts: 1281
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11962
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic