Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test that two Joda-Time DateTime objects are nearly equal?

In unit tests I often have methods that return a DateTime on or about now(). Is there a way to say that the actual DateTime is within a few seconds of the actual DateTime?

like image 651
Drew Stephens Avatar asked Jan 20 '23 15:01

Drew Stephens


1 Answers

That sounds like a bad idea. Unit tests should not depend in any way on the real current time... this is why it's a good practice to inject some interface, called Clock perhaps, in your class's constructors and use that as the source for the current time. Then in your unit tests you can use a special implementation of that for which you can control the time it returns, making your tests deterministic.

That said, I'm sure you could easily write a method that checks that a DateTime is within a certain range of another DateTime by creating new DateTimes by adding and subtracting the desired number of seconds and then comparing.

like image 85
ColinD Avatar answered Jan 31 '23 01:01

ColinD