Reputation: 929
I'm trying out TDD on some side project and already encountered this a couple of times.
As an example, my program needs to take a number X, and find out the date string that was X days ago, in order to perform certain date-based queries.
So I figured I need a test that validates the date computation is correct.
But, since the test depends on the current date, how can create such a test?
I can have the test method implement this exact functionality by itself, but that would just make it redundant...
Edit: I've seen Setting time and date in JUnit test fixture but the answers there seem quite an overkill to what I was trying to achieve.
Upvotes: 4
Views: 770
Reputation: 736
Consider adding another layer of abstraction.
Instead of using the current date, the code that performs the query takes in any date, and the number of days to subtract from that date.
Do you testing on this function, and then your higher level function will just always pass in the current date.
// don't bother testing this function
def get_some_day_before_today(num_days_ago):
return get_some_day_before_some_date(num_days_ago, Date.now())
// do test this function
def get_some_day_before_some_date(num_days_before, reference_date):
// do stuff
return earlierDate
EDIT: Some example tests
def test_zero_days():
zero_days_before = get_some_day_before_some_date(0, "01/01/16")
assert_equals("01/01/16", zero_days_before)
def test_one_day():
one_day_before = get_some_day_before_some_date(1, "02/01/16")
assert_equals("01/01/16", one_day_before)
Upvotes: 3