Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hamcrest Date Matchers

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?

like image 525
smp7d Avatar asked Dec 23 '11 20:12

smp7d


People also ask

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

What is a matcher in Hamcrest?

Hamcrest is a framework for writing matcher objects allowing 'match' rules to be defined declaratively. There are a number of situations where matchers are invaluable, such as UI validation or data filtering, but it is in the area of writing flexible tests that matchers are most commonly used.

How do I import my Hamcrest matchers?

First, click “assertThat” and then press alt+Enter then click “Static Import Method…” Then click “is” and press alt+enter and select “Static Import Method…” Then, select “Is.is(org. hamcrest.


2 Answers

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.

like image 174
Tom Anderson Avatar answered Oct 07 '22 13:10

Tom Anderson


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()); 
like image 23
stewbis Avatar answered Oct 07 '22 15:10

stewbis