I was wondering if there is a way to mock Date and Calendar objects for testing purposes. In other words I want to programatically be able to change what new Date() and new Calendar() etc. returns independent of the system date. Something like setting the date for the jvm or something. I have no clue how it could be done.

Any thoughts?

well, of course you can, just write your own Date class.
but you can always set the date you want using the mutators.

Writing my own date class insn't an option at the moment. there's a lot of code already creating date and Calendar object in various ways that I don't know anything about. I want to set the system date and time externally without touching any code that accesses dates.

Class Date extends Date//the original one
public Date(){
setDay(..); setMonth(..); setYear(..);

and so .. how would that ruin all the code you have so far?

I would have to change all Date references to point to the new Date class.

just the imports.

but yes, either you have to change all the imports everywhere you use it, or you have to set the values (in exactly the same classes). IMHO, changing the imports would be the least effort.

especially since when you're done with it, and your own Date class, your compiler will pick up on the fact that you're using (importing) a non existing class, the error messages will tell you where to change the imports.

if you just use mutators, chance is, that when you try to rollback, you forget some classes, and you'll end up with hardcoded values for the dates, which not what you want at all.

Yes I know that would work, but It's not possible. Its a huge system used in production with jars that it depend on that I don't have the sources to.

well ... how do you expect to change/inject values into code that you can't control?
you could always set the system date on your machine, I guess, but I'm not sure what good that would do you.

I've never tried this but maybe you can create your own TimeZone that has a rawOffset that shifts the date to where you want it to be, then set that custom TimeZone for your program???

Edited 4 Years Ago by JamesCherrill: Chnaged "Locale" to "TimeZone"

Hmm, it sound like it might work, but would I really be able to shift the time as much as I want back and forward?

Who's your daddy!

SimpleTimeZone tz = new SimpleTimeZone(-10*24*60*60*1000,"10 days ago");
System.out.println(new Date());

(dances round PC throwing punches in the air)

Celebrations maybe a bit premature - Max integer value limits offset to about +/- 24 days.
Is this enough?

Edited 4 Years Ago by JamesCherrill: int limit = 24 days offset

Actually that would be P. Brinkhof, but still a very impressive answer/sollution :)

Hello Daddy! A couple of days might actually be enough. Gonna try this. Thanks!

This question has already been answered. Start a new discussion instead.