Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit date-time comparison with uncertainty

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?

like image 480
Dims Avatar asked Sep 05 '15 06:09

Dims


2 Answers

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));
like image 91
Peter Lawrey Avatar answered Oct 21 '22 12:10

Peter Lawrey


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.

like image 5
Florian Schaetz Avatar answered Oct 21 '22 11:10

Florian Schaetz