Skip to content

Instantly share code, notes, and snippets.

@kaushikgopal
Created October 3, 2016 21:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kaushikgopal/9d134b0aef2ca254765f2d9b31a06978 to your computer and use it in GitHub Desktop.
Save kaushikgopal/9d134b0aef2ca254765f2d9b31a06978 to your computer and use it in GitHub Desktop.
DateSubject - custom Truth extension subject for comparing Dates
import com.google.common.truth.FailureStrategy;
import com.google.common.truth.Subject;
import com.google.common.truth.SubjectFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static com.google.common.truth.Truth.assert_;
public class DateSubject
extends Subject<DateSubject, Date> {
private static final SubjectFactory<DateSubject, Date> FACTORY = new SubjectFactory<DateSubject, Date>() {
@Override
public DateSubject getSubject(FailureStrategy fs, Date target) {
return new DateSubject(fs, target);
}
};
private DateSubject(FailureStrategy failureStrategy, Date subject) {
super(failureStrategy, subject);
}
/**
* Use this for a convenient API call like so:
* DateSubject.assertThat(date1).isTheSameDay(date2);
*/
public static DateSubject assertThat(Date testDate) {
return assert_().about(date()).that(testDate);
}
public DateSubject isTheSameDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String dateString1 = sdf.format(getSubject());
String dateString2 = sdf.format(date);
if (!dateString1.equalsIgnoreCase(dateString2)) {
fail(String.format(Locale.getDefault(),
"date's don't appear to be the same \n[%s]\n[%s]",
dateString1,
dateString2));
}
return this;
}
public DateSubject isNotTheSameDay(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
String dateString1 = sdf.format(getSubject());
String dateString2 = sdf.format(date);
if (dateString1.equalsIgnoreCase(dateString2)) {
fail(String.format(Locale.getDefault(),
"date's appear to be the same \n[%s]\n[%s]",
dateString1,
dateString2));
}
return this;
}
static SubjectFactory<DateSubject, Date> date() {
return FACTORY;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment