Skip to content

Instantly share code, notes, and snippets.

@Koriit
Last active May 7, 2022 18:45
Show Gist options
  • Save Koriit/0d2d41322f63adb63ef50267f65e95bf to your computer and use it in GitHub Desktop.
Save Koriit/0d2d41322f63adb63ef50267f65e95bf to your computer and use it in GitHub Desktop.
Hamcrest matcher for OffsetDateTime
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import java.time.OffsetDateTime;
import java.time.format.DateTimeParseException;
import static java.time.format.DateTimeFormatter.ISO_OFFSET_DATE_TIME;
/**
* Matcher to validate date-time strings. Can also be used as equals matcher for offset date-time.
* <p/>
* Example result:
* <p>
* java.lang.AssertionError: JSON path "$.content[*].date"<br/>
* Expected: every item is is offset date-time and matches the format of '2011-12-03T10:15:30.123Z'<br/>
* but: an item was a java.lang.Long (<1611068097209L>)
*/
public class OffsetDateTimeMatcher extends TypeSafeMatcher<String> {
private OffsetDateTime value = null;
public static OffsetDateTimeMatcher isOffsetDateTime() {
return new OffsetDateTimeMatcher();
}
public static OffsetDateTimeMatcher isOffsetDateTime(String date) {
OffsetDateTimeMatcher matcher = new OffsetDateTimeMatcher();
matcher.value = OffsetDateTime.parse(date);
return matcher;
}
@Override
public boolean matchesSafely(String argument) {
try {
OffsetDateTime date = OffsetDateTime.parse(argument);
return value == null || value.isEqual(date);
} catch (DateTimeParseException e) {
return false;
}
}
@Override
public void describeTo(Description description) {
if (value == null) {
description.appendText("offset date-time and matches the format of '2011-12-03T10:15:30.123Z'");
} else {
description.appendText("offset date-time and equal to '" + ISO_OFFSET_DATE_TIME.format(value) + "'");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment