Android unit test中通过颜色比对替代肉眼检查

对于Android UI类的单元测试,以前写的有些代码就是sleep 10秒,然后肉眼检查下。这样子在自动化测试中没有用。

今天修改了下代码,其实肉眼检查也就是检查pixel的颜色,所以可以直接获取view的某个点的颜色,然后跟期望值比较就行了。

这是获取view中某个pixel颜色的代码:

    public static int getColor(View view, int x, int y) {
        int w = view.getWidth();
        int h = view.getHeight();
        if (x >= 0 && x < w && y >= 0 && y < h) {
            Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bmp);
            view.draw(canvas);
            return bmp.getPixel(x, y);
        }
        return 0;
    }

如果只需要颜色相近,而不完全相同,可以计算两个颜色的四元素(RGBA)之间的距离,可以用这个方法:

    public static int getColorDistance(int color1, int color2) {
        return (int) Math.sqrt(
                (Math.pow(Color.red(color1) - Color.red(color2), 2)
                + Math.pow(Color.green(color1) - Color.green(color2), 2)
                + Math.pow(Color.blue(color1) - Color.blue(color2), 2)
                + Math.pow(Color.alpha(color1) - Color.alpha(color2), 2)));
    }

 

posted @ 2015-07-02 17:38  西城铁  阅读(223)  评论(0编辑  收藏  举报