Я разрабатываю приложение для Android, и я пытаюсь протестировать один экран, который показывает список элементов.Список реализован с использованием RecyclerView, и каждый элемент имеет имя (TextView) и изображение (ImageView).Для проверки имени первого элемента я использую следующий код:
private static int ANY_ELEMENT_POSITION = 0;
@Test
public void thatAnyElementTitleIsDisplayed() {
givenBuildingActivity();
whenNoAction();
thenAnyElementTitleIsDisplayed();
}
private void givenBuildingActivity() {
}
private void whenNoAction() {
}
private void thenAnyElementTitleIsDisplayed() {
onView(withRecyclerView(R.id.buildings_container)
.atPositionOnView(ANY_ELEMENT_POSITION, R.id.building_title))
.check(matches(withText("some name")));
}
Этот фрагмент кода работает.Но сейчас я пытаюсь проверить, что изображение одного элемента загружается и отображается на экране.Во-первых, у меня есть ImageMatcher, который тестирует ресурс изображения так же, как показано при просмотре изображения.Но проблема в том, что изображение показывается через библиотеку Picasso, поэтому оно загружается асинхронно, а затем, когда я запускаю тест, оно не работает.У меня следующий код:
@Test
public void thatAnyElementImageIsDisplayed() {
givenBuildingActivity();
whenNoAction();
thenAnyElementImageIsDisplayed();
}
private void thenAnyElementImageIsDisplayed() {
onView(withRecyclerView(R.id.buildings_container)
.atPositionOnView(ANY_ELEMENT_POSITION, R.id.building_image))
.check(matches(withDrawable(R.drawable.building_placeholder)));
}
DrawableMatcher следующий:
public class DrawableMatcher extends TypeSafeMatcher<View> {
private final int expectedId;
private String resourceName;
static final int EMPTY = -1;
static final int ANY = -2;
DrawableMatcher(int expectedId) {
super(View.class);
this.expectedId = expectedId;
}
@Override
protected boolean matchesSafely(View target) {
if (!(target instanceof ImageView)) {
return false;
}
ImageView imageView = (ImageView) target;
if (expectedId == EMPTY) {
return imageView.getDrawable() == null;
}
if (expectedId == ANY) {
return imageView.getDrawable() != null;
}
Resources resources = target.getContext().getResources();
Drawable expectedDrawable = resources.getDrawable(expectedId);
resourceName = resources.getResourceEntryName(expectedId);
if (expectedDrawable == null) {
return false;
}
Bitmap bitmap = getBitmap(imageView.getDrawable());
Bitmap otherBitmap = getBitmap(expectedDrawable);
return bitmap.sameAs(otherBitmap);
}
private Bitmap getBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
@Override
public void describeTo(Description description) {
description.appendText("with drawable from resource id: ");
description.appendValue(expectedId);
if (resourceName != null) {
description.appendText("[");
description.appendText(resourceName);
description.appendText("]");
}
}
}
Подводя итог, я думаю, что основная проблема - это Пикассоасинхронная загрузка изображения.Итак, есть ли способ сделать тест, который я хочу?
Спасибо за ответы