Skip to content

Instantly share code, notes, and snippets.

@mid0111
Last active October 10, 2015 18:58
Show Gist options
  • Save mid0111/3736106 to your computer and use it in GitHub Desktop.
Save mid0111/3736106 to your computer and use it in GitHub Desktop.
Custom Date Matcher for JUnit4
package sample;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
public class IsDate extends BaseMatcher<Date> {
private final int yyyy;
private final int mm;
private final int dd;
Object actual;
IsDate(int yyyy, int mm, int dd) {
this.yyyy = yyyy;
this.mm = mm;
this.dd = dd;
}
public static Matcher<Date> dateOf(int yyyy, int mm, int dd) {
return new IsDate(yyyy, mm, dd);
}
@Override
public boolean matches(Object actual) {
this.actual = actual;
if (!(actual instanceof Date)) {
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTime((Date) actual);
if (yyyy != cal.get(Calendar.YEAR) ||
mm != cal.get(Calendar.MONTH) + 1 ||
dd != cal.get(Calendar.DATE)) {
return false;
}
return true;
}
@Override
public void describeTo(Description desc) {
desc.appendValue(this.yyyy + "/" + this.mm + "/" + this.dd);
if (actual != null) {
desc.appendText(" but actual is ");
desc.appendValue(new SimpleDateFormat("yyyy/MM/dd").format((Date) actual));
}
}
}
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static sample.IsDate.*;
public class Test {
@Test
public void sample() {
assertThat(new Date(), is(dateOf(2012, 1, 12)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment