检查双精度值时,通常为asserEquals()中的比较函数提供精度(delta)

如何对日期时间值做同样的事情?假设我不想与微秒精度进行比较,而是希望检查一些不精确的计时。

如何做到这一点?

最佳答案

就个人而言,我会为此编写一个简单的Hamcrest风格Matcher ...

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

这样,您可以使用静态导入来简单地编写...
assertThat( myDate, closeToDate( someDate, 1000 ) ); // for 1000ms tolerance

...如果您问我,它的可读性很好。

08-06 08:35