When checking for double values, it is normal to provide precision (delta) for comparison functions, like in asserEquals()
How to do the same for date-time values? Suppose I don't wish to compare with microsecond precision, but wish to check some inexact timings.
How to accomplish that?
If you have Date, you can use the built in error.
assertEquals(date1.getTime(), date2.getTime(), 1);
If you have a LocalDateTime, you can compare the truncated times.
assertEquals(ldt1.truncatedTo(ChronoUnit.MILLI_SECONDS),
ldt2.truncatedTo(ChronoUnit.MILLI_SECONDS));
Personally, I would just write a simple Hamcrest style Matcher for it...
class CloseToDate extends BaseMatcher<Date> {
private Date closeTo;
private long deltaInMs;
public CloseToDate(Date closeTo, long deltaInMs) {
this.closeTo = closeTo;
this.deltaInMs = deltaInMs;
}
@Override
public boolean matches(Object arg0) {
if (!(arg0 instanceof Date)) {
return false;
}
Date date = (Date)arg0;
return Math.abs( date.getTime() - closeTo.getTime()) <= deltaInMs;
}
@Override
public void describeTo(Description arg0) {
arg0.appendText(String.format("Not more than %s ms from %s", deltaInMs, closeTo));
}
public static CloseToDate closeToDate(Date date, long deltaInMs) {
return new CloseToDate(date, deltaInMs);
}
}
This way you can use static imports to simply write...
assertThat( myDate, closeToDate( someDate, 1000 ) ); // for 1000ms tolerance
...which is, if you ask me, pretty well readable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With