LoginSignup
0
1

More than 5 years have passed since last update.

AssertJのCustom assertionを作る

Posted at

AssertJについてはこの辺参照

Custom assertionを作るにあたってはこちらを参考にさせて頂いた

作ったもの

public static class ImageViewAssert extends AbstractAssert<ImageViewAssert, ImageView> {
    public ImageViewAssert(ImageView actual) {
        super(actual, ImageViewAssert.class);
    }

    public static ImageViewAssert assertThat(ImageView actual) {
        return new ImageViewAssert(actual);
    }

    public ImageViewAssert hasDrawable(Drawable drawable) {
        isNotNull();
        Drawable actualDrawable = actual.getDrawable();

        if (sameBitmap(actualDrawable, drawable)) {
            failWithMessage("error");
        }

        return this;
    }

    public ImageViewAssert hasDrawable(int resId) {
        isNotNull();
        Context context = InstrumentationRegistry.getTargetContext();
        Drawable drawable = ((BitmapDrawable) context.getResources().getDrawable(resId));
        Drawable actualDrawable = actual.getDrawable();

        if (!sameBitmap(actualDrawable, drawable)) {
            failWithMessage("error");
        }

        return this;
    }

    private boolean sameBitmap(Drawable actual, Drawable expected) {
        Bitmap actualBitmap = ((BitmapDrawable) actual).getBitmap();
        Bitmap expectedBitmap = ((BitmapDrawable) expected).getBitmap();

        return actualBitmap.sameAs(expectedBitmap);
    }
}

その他

もともと、assertj-androidhasDrawableというメソッドは用意されてたんだけど、xmlのsrcにセットしてて、それを比較する場合に上手く動かなかったので、Bitmapで比較するようにした。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1