ANTLR和StringTemplate執行個體:自動產生單元測試類,

來源:互聯網
上載者:User

ANTLR和StringTemplate執行個體:自動產生單元測試類,
ANTLR和StringTemplate執行個體:自動產生單元測試類1. ANTLR文法

要想自動產生單元測試,首先第一步就是分析被測試類別。這裡以Java代碼為例,用ANTLR對Java代碼進行分析。要想靠自己完全手寫出一門語言的ANTLR文法檔案的複雜程度難以想象,很貼心的是在ANTLR的GitHub網站上列出了很多常見語言的文法檔案,例如Java,Sqlite和MySQL的SQL文法等。

有了.g4文法檔案,按照Antlr v4入門教程和執行個體中的步驟,就能自動產生出解析器的代碼,這裡就不再詳述了。

2. StringTemplate基礎

StringTemplate(簡稱ST)也是ANTLR提供的一個非常好用的工具。它的功能類似於Velocity、FreeMaker等模板引擎,可以根據事先定義好的模板,在運行時根據不同的傳值渲染出不同的網頁、郵件、代碼等。但從名稱中的String就能看出,它是比較輕量級的。試用了一下的確如此,支援在Java中寫入程式碼簡單的模板。

但試用過程中還是碰到了有不少問題,總感覺它的模板文法有些複雜啊!而且最新的ST4的API與之前版本發生了很大變化,網上找的很多例子都不好用了。具體還是參考官網的教程吧,以及這個CheatSheet表格。當然,還有花了不少時間調試好的本文的程式碼範例!

3. 單元測試產生器

首先來看Main方法。輸入文本就是code變數表示的一個Java類,裡面有兩個方法。然後使用自動產生出的ANTLR代碼,構建起語義分析器和解析器的處理鏈,並傳入UnitTestGenerator監聽器對輸入文本進行遍曆。

public class JavaCodeParseTest {    public static void main(String[] args) {        String code =                "package com.jcache.store;" +                "public class CacheStore {" +                    "Object getCache(int a) {" +                        "if (a == 1)" +                            "return 1;" +                        "else " +                            "return 2;" +                    "}" +                    "void setCache(int a) {" +                        "return;" +                    "}" +                "}";        // 1.Lexical analysis        JavaLexer lexer = new JavaLexer(new ANTLRInputStream(code));        CommonTokenStream tokens = new CommonTokenStream(lexer);        // 2.Syntax analysis        JavaParser parser = new JavaParser(tokens);        ParseTree tree = parser.compilationUnit();        // 3.Application based on Syntax Tree        ParseTreeWalker walker = new ParseTreeWalker();        walker.walk(new UnitTestGenerator(), tree);    }}

下面就來看一個核心代碼UnitTestGenerator的實現。
這裡簡單說一下代碼中的幾個關鍵點:

  • ST模板組:在模板檔案中定義比較簡單,如果要在Java中定義模板的話,一定要參照本例static初始化塊的寫法。
  • 嵌套子模板和Multi-valued:要想根據方法名列表,自動為每個方法名都產生一個方法,就需要按照
/** * Simple unit test generator. */public class UnitTestGenerator extends JavaBaseListener {    /** Constants: template name, placeholder name, generated code name */    private static final String CLASS_ST_NAME = "classST";    private static final String METHOD_ST_NAME = "methodST";    private static final String TEST_PKG_NAME = "testPkgName";    private static final String TEST_CLASS_NAME = "testClassName";    private static final String TEST_METHOD_NAME = "testMethodName";    private static final String CLASS_NAME_SUFFIX = "Test";    private static final String METHOD_NAME_PREFIX = "test";    /** Template for Java */    private static final String METHOD_ST =            t("@Test") +            t("public void " + $(TEST_METHOD_NAME) + "() throws Exception {") +            tt("//body...") +            t("}") +            n("");    private static final String CLASS_ST =            n("package " + $(TEST_PKG_NAME) + ";") +            n("") +            n("import org.junit.*;") +            n("") +            n("public class " + $(TEST_CLASS_NAME) + " {") +            n("") +            /**             * Apply nested template 'methodST' to multi-valued attributes 'testMethodName'.             * NOTE: <attribute:template(argument-list)>             *      Apply template to attribute with optional argument-list.             *      Example: <name:bold()> applies bold() to name's value.             *      The first argument of the template gets the iterated value.             */            n($(TEST_METHOD_NAME + ":" + METHOD_ST_NAME +"();separator=\"\n\"")) +            n("}");    /** ST group to nest template */    private static STGroup group;    static {        group = new STGroup('$', '$');        CompiledST classST = group.defineTemplate(CLASS_ST_NAME, CLASS_ST);        classST.addArg(new FormalArgument(TEST_PKG_NAME));        classST.addArg(new FormalArgument(TEST_CLASS_NAME));        classST.addArg(new FormalArgument(TEST_METHOD_NAME));        CompiledST methodST = group.defineTemplate(METHOD_ST_NAME, METHOD_ST);        methodST.addArg(new FormalArgument(TEST_METHOD_NAME));    }    /** Attributes. NOTE: group.getInstanceOf() return new ST */    private Map<String, Object> attributeMap = new HashMap<>();    @Override    public void enterPackageDeclaration(@NotNull JavaParser.PackageDeclarationContext ctx) {        attributeMap.put(TEST_PKG_NAME, ctx.qualifiedName().getText());    }    @Override    public void enterClassDeclaration(@NotNull ClassDeclarationContext ctx) {        String orgClassName = ctx.Identifier().getText();        String testClassName = orgClassName + CLASS_NAME_SUFFIX;        attributeMap.put(TEST_CLASS_NAME, testClassName);    }    @Override    public void enterMethodDeclaration(@NotNull MethodDeclarationContext ctx) {        String orgMethodName = ctx.Identifier().getText();        String testMethodName = METHOD_NAME_PREFIX + orgMethodName.substring(0, 1).toUpperCase()                + orgMethodName.substring(1);        // Multi-valued attribute        List<String> methodNames = (List<String>) attributeMap.get(TEST_METHOD_NAME);        if (methodNames == null) {            methodNames = new ArrayList<>();            attributeMap.put(TEST_METHOD_NAME, methodNames);        }        methodNames.add(testMethodName);    }    @Override    public void enterStatement(@NotNull StatementContext ctx) {        // If/else/switch, for/while, try-catch        switch (ctx.getStart().getText()) {            case "if":                break;            case "for":                break;            case "try":                break;            default:                break;        }    }    @Override    public void exitCompilationUnit(@NotNull JavaParser.CompilationUnitContext ctx) {        ST template = group.getInstanceOf(CLASS_ST_NAME);        attributeMap.entrySet().forEach(e -> template.add(e.getKey(), e.getValue()));        System.out.println(template.render());        // Cleanup        attributeMap.clear();    }    // =======================================    //          String Utility    // =======================================    private static String $(String attrName) {        return "$" + attrName + "$";    }    private static String n(String str) {        return str + "\n";    }    private static String t(String str) {        return "\t" + n(str);    }    private static String tt(String str) {        return "\t\t" + n(str);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.