Sowmiya
Sowmiya

Reputation: 313

Date and DateTime handling - A particular scenario fails

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 ?

Upvotes: 0

Views: 182

Answers (2)

nobeh
nobeh

Reputation: 10039

Let's say, you use new Date() for the notion of today. You should preserve the date for comparison; I believe this is the root of the issue, you need to preserve expected values before and after query execution to be testable/verifiable:

Date today = new Date();

// update the data layer using today

Date recordedDate = // fetch the date that is recorded

assertEquals(today, recordedDate);

Presumably, you'll use some other facility such as java.util.Calendar to calculate the time points mentioned in your question.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500923

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 a Clock interface with a single method (now() or something similar) returning whatever representation of "now" you want to use. (Personally I'd use Instant from Joda Time but it's up to you.)

Now inject a Clock into 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.

Upvotes: 5

Related Questions