开发者

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

开发者 https://www.devze.com 2023-02-07 02:37 出处:网络
In unit tests I often have methods t开发者_如何学Gohat 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? That sounds li

In unit tests I often have methods t开发者_如何学Gohat 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?


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.


Turns out, this is pretty easy with Joda Time:

Duration dur = new Duration(sender.getStartTime(), new DateTime());
assertTrue(5000 > dur.getMillis());
0

精彩评论

暂无评论...
验证码 换一张
取 消