by shigemk2

当面は技術的なことしか書かない

カスタムMatcherを作ろう

日付の比較検証を行うカスタムMatcherの要件

  1. クラスを作成する
  2. ファクトリメソッドを作成する
  3. コンストラクタを定義する
  4. matchesメソッドを実装する
  5. describeToメソッドを実装する
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;
  }

  @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)) return false;
    if (mm != cal.get(Calendar.MONTH) + 1) return false;
    if (dd != cal.get(Calendar.DATE)) return false;
    return true;
  }

  @Override
  public void describeTo(Description desc) {
      desc.appendValue(String.format("%d/02d/%02d", yyyy, mm, dd));
      if (actual != null) {
          desc.appendText(" but actual is ");
          desc.appendValue(
           new SimpleDateFormat("yyyy/MM/dd").format((Date) actual));
      }
  }

  public static Matcher<Date> dateOf(int yyyy, int mm, int dd) {
      return new IsDate(yyyy, mm, dd);
  }
}