Hamcrest Date Matchers
Solution 1
The OrderingComparison::greaterThan matcher will work on any type which is comparable to itself (it's in the org.hamcrest.number
package, but it's not actually number-specific). Date is such a type.
Solution 2
There is a library of hamcrest date matchers provided by the library at https://github.com/eXparity/hamcrest-date which is also available for maven, ivy, etc at
<dependency>
<groupId>org.exparity</groupId>
<artifactId>hamcrest-date</artifactId>
<version>1.1.0</version>
</dependency>
It supports various matchers for dates so allows constructs such as
Date myBirthday = new Date();
MatcherAssert.assertThat(myBirthday, DateMatchers.after(Moments.today()));
or
Date myBirthday = new Date();
MatcherAssert.assertThat(myBirthday, DateMatchers.isToday());
Solution 3
You can have a look at the new Date Matchers that will be added to hamcrest (I don't know when thought):
Date matchers discussion/code changes on github
After a quick look it seems there will be a new package org.hamcrest.date containing:
- IsAfter
- IsBefore
- IsSameDayOfTheMonth
- IsSameDayOfTheWeek
- IsSameDayOfTheYear
- IsSameHour
- IsSameInstant
- IsSameMinute
- IsSameMonth
- IsSameSecond
- IsSameYear
- IsWithin
Solution 4
There are certain hamcrest extensions that can ease some of the testing related to dates. Please check here.
Solution 5
The Matchers#greaterThan
matcher works with Date
s and other Comparable
objects.
Here's the way to check that your date is greater than or equal (≥) to some expected date:
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.AnyOf.anyOf;
...
Date expectedMin = new Date()
// Execute the method being tested
Date resultDate = getDate();
// Validate
assertThat(resultDate, anyOf(greaterThan(expectedMin), equalTo(expectedMin)))
Comments
-
smp7d over 3 years
I need to test before/after on dates in a certain test case. I'd like to use Hamcrest matchers if possible.
Are there any matchers for Hamcrest (Java) for working with Dates? If so, what package/class would I find the particular date matcher functions in?
-
Tom Anderson over 10 yearsThanks. It seems they've got rid of the class in favour of a static factory method, which makes a really stable link impossible, but i've fixed it as far as i can.
-
JeanValjean over 8 yearsThat's true. There are also extensions that provide some more easy-to-read methods. E.g., Cirneco provides the matcher
J7Matchers::after
that is an alias forOrderingComparison::greaterThan
. From my point of view, sematic is always important in unit test, that's why I usually prefer the fulent approach provided by Google Truth, but I sometimes have to handle with Hamcrest in legacy projects. -
Oleksandr Tarasenko over 4 yearsHow is this related to the topic?