I will have to write test cases to check the working of some queries say,which retrieves records with date today, next_week, previous_year and the like.
Its a junit test case basically, which I am implementing by:
1.Inserting records with date corresponding to TODAY,NEXT_WEEK,PREVIOUS_YEAR
2.So, I will know for a particular query, what are the records to be returned, I will execute the query, retrieve the records for a particular condition and check it for the correct records.
In this procedure, while executing TODAY’s case, I am facing a problem.
If I run my test case by the midnight, say 11.59, first insertion of data will happen, which will insert a date,say 24-4-2012T11:59:00.00
And before the execution of the query, the date becomes tomorrow, that is 25-4-2012T00:00:00.00
The TODAY condition will execute the query with 25th not 24th. So my testcase fails.
How can I resolve this problem ?
Write more testable code 🙂
My guess is that you’re taking “the current date” using
System.currentTimeMillis(),Calendar.getInstance()or something similar. That code can’t easily be intercepted to give you “whatever value you want”. Instead, introduce aClockinterface with a single method (now()or something similar) returning whatever representation of “now” you want to use. (Personally I’d useInstantfrom Joda Time but it’s up to you.)Now inject a
Clockinto the code you want to test, e.g. as a parameter constructor. For tests, use a stub implementation which returns whatever you want it to. For production, use a “real” implementation.