使用 Espresso 测试可绘制更改

新手上路,请多包涵

我是 Espresso 测试的新手,但似乎没有任何方法可以测试可绘制的更改。

我有一个教程是 ImageView Drawable 幻灯片“塞进”半透明 TextView 在我的测试中,我想确保在按下下一个按钮时,正确的 Drawable 已插入到教程的 ImageView 中。

没有默认的 Matcher 来检查 Drawable s,所以我开始使用 https://stackoverflow.com/a/28785178/981242 编写自己的代码。不幸的是,由于无法检索 ImageView 的活动 Drawable 的 ID,我无法完成 matchesSafely()

这不可能是测试活动 Drawable 的唯一用例。人们通常在这种情况下使用什么工具?

原文由 nukeforum 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 304
2 个回答

我不想比较位图,而是遵循这个答案的建议: https ://stackoverflow.com/a/14474954/1396068

设置图像视图的可绘制对象时,还要将可绘制对象 ID 存储在其标记中 setTag(R.drawable.your_drawable) 。然后使用 Espresso 的 withTagValue(equalTo(R.drawable.your_drawable)) 匹配器来检查正确的标签。

原文由 Fabian Streitel 发布,翻译遵循 CC BY-SA 4.0 许可协议

请查看我找到的本教程。似乎工作得很好 https://medium.com/@dbottillo/android-ui-test-espresso-matcher-for-imageview-1a28c832626f#.4snjg8frw

这是复制面食的摘要;-)

 public class DrawableMatcher extends TypeSafeMatcher<View> {

    private final int expectedId;
    String resourceName;

    public 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 < 0){
            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 = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
        Bitmap otherBitmap = ((BitmapDrawable) expectedDrawable).getBitmap();
        return bitmap.sameAs(otherBitmap);
    }

    @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("]");
        }
    }
}

请注意,这仅在您的 DrawableBitmapDrawable 时有效。如果你还有 VectorDrawable 或其他 Drawable 你必须检查这个( imageView.getDrawable() instanceOf XXXDrawable )并从中获取位图。除了你有某种简单的 Drawable,你只有一种颜色,所以你可以比较。

例如,要获取 VectorDrawable 的位图,您必须将 VectorDrawable 绘制到画布并将其保存到位图(我在为 VectorDrawable 着色时遇到了一些麻烦)。如果您有一个 StateListDrawable,您可以获得所选状态的 Drawable 并重复您的 if instanceOf 级联。其他的Drawable类型我没有任何经验,sorry!

原文由 wolle 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题