Dims
Dims

Reputation: 51059

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?

Upvotes: 8

Views: 4173

Answers (4)

Florian Lopes
Florian Lopes

Reputation: 1289

You can use https://github.com/eXparity/hamcrest-date#usage

LocalDateTime myAppointment = LocalDateTime.of(2015, AUGUST, 9, 10, 30, 0);
assertThat(LocalDateTime.now(), within(15, MINUTES, myAppointment));

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533550

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));

Upvotes: 6

Florian Schaetz
Florian Schaetz

Reputation: 10652

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.

Upvotes: 5

Amila
Amila

Reputation: 5213

You could convert to String using same format (to whatever the precision you want) and compare the two strings.

Upvotes: 1

Related Questions