アナログ金木犀

つれづれなるまままにつれづれする

テスト書いてないとエラーになるCustom Lint書いた

作り方とかは基本的には下記の記事と同じ流れです。

motida-japan.hatenablog.com

なのでDetectorだけ紹介。

public class MustWriteTestDetector extends Detector implements Detector.JavaScanner {

:

    @Override
    public AstVisitor createJavaVisitor(@NonNull JavaContext context) {
        return new TestChecker(context);
    }

    private static class TestChecker extends ForwardingAstVisitor {
        private final JavaContext context;

        private TestChecker(JavaContext context) {
            this.context = context;
        }

        @Override
        public boolean visitClassDeclaration(ClassDeclaration node) {
            String name = node.astName().astValue();
            if (node.getParent() instanceof CompilationUnit) {

                CompilationUnit parent = (CompilationUnit) node.getParent();

                if (parent.astPackageDeclaration() != null
                        && parent.astPackageDeclaration().getPackageName().startsWith("YOUR_PACKAGE_NAME)) {

                    boolean isTarget = false;

                    // テストを書きたいターゲットにかどうかのロジックをここに書く
                    :

                    if (isTarget) {
                        String packageName = parent.astPackageDeclaration().getPackageName();
                        String testFilePath = context.getProject().getDir().getAbsolutePath() + File.separator +
                                "src" + File.separator +
                                "test" + File.separator +
                                "java" + File.separator +
                                packageName.replace(".", File.separator) + File.separator +
                                name + "Test.java";
                        if (!new File(testFilePath).exists()) {
                            context.report(ISSUE, context.getLocation(node), "not found test code at \"" + testFilePath + "\"");
                        }
                    }
                }
            }

            return super.visitClassDeclaration(node);
        }

    }

}
  • AstVisitorを作る
  • クラス宣言時に、自分のアプリで、かつ諸々自分がテストを書くべきと思ってるがテストファイルがないものを検知

ということをやっています。

即席なので自分のアプリのパッケージ名なんかを条件に入れちゃってます。ごめんなさい。

もう少し真面目にやるなら、設定ファイルとかをプロジェクトルートにおいて、それの有無で動作するしない、テスト対象かどうかはその設定ファイルに、とするといいかもしれない。