ただ、JUnit作成時に「こんなチェックをしたいのに、標準で用意されていない」こともあります。
このような場合、自作するしかありません。
次のような作業が必要です。
- BoundedMatcherを実装したオブジェクトを戻り値とするモジュールを作成
- マッチしているかどうか判定するモジュール、matchesSafelyをオーバーライドして判定ロジックを作成
- 何を判定するMatcherなのかを記述するdescribeToをオーバーライドして実装
Espressoのソースが公開されていますので、参考になります。
ViewMatchersクラス:https://code.google.com/p/android-test-kit/source/browse/espresso/lib/src/main/java/com/google/android/apps/common/testing/ui/espresso/matcher/ViewMatchers.java
次はTextViewのColorが一致しているかどうか判定するMatcherのサンプルプログラムです。
public static Matcher<view> withTextColor(final int resourceId) {
return new BoundedMatcher<view textview="">(TextView.class) {
private int expectedColor = -1;
private String resourceName;
@Override
protected boolean matchesSafely(TextView textView) {
if (expectedColor == -1) {
try {
expectedColor = textView.getResources().getColor(resourceId);
resourceName = textView.getResources().getResourceEntryName(resourceId);
} catch (Resources.NotFoundException ignored) {
// view could be from a context unaware of the resource id.
}
}
if (expectedColor != -1) {
return (expectedColor == textView.getCurrentTextColor());
} else {
return false;
}
}
@Override
public void describeTo(Description description) {
description.appendText("with color from resource id: ");
description.appendValue(resourceId);
if (null != resourceName) {
description.appendText("[");
description.appendText(resourceName);
description.appendText("]");
}
if (-1 != expectedColor) {
description.appendText(" value: ");
description.appendText(String.valueOf(expectedColor));
}
}
};
}

0 件のコメント:
コメントを投稿