有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java文档化TestNG测试用例

是否有方法记录testNG测试用例,以便自动生成文档?我会想象这样的情况:

@Description("This testcase checks, whether the system is alive")
@Step("Check whether services are running")
@Step("Try to access the system webpage")
...
@Test(groups={"sanity"})
public void checkStatus() {
...
}

我考虑了两个自定义处理和编写javadoc的选项。在我尝试这些选择之前,我想知道是否有一个标准的方法来做这件事。我当然希望重用当前的testNG注释,尤其是测试分组

最后但并非最不重要的一点是,我只想将此方法用于系统级测试(而不是单元测试),这非常复杂,而且仅从测试名称或其代码来说明测试做了什么并不容易


共 (1) 个答案

  1. # 1 楼答案

    最后,我自己弄明白了。我使用javadoc结合一些注释处理(只是为了区分测试用例组)。我使用自定义doclet,它首先以以下方式构建测试用例列表:

    private MethodDoc[] getTestMethods(RootDoc root) {
        List<MethodDoc> result = new ArrayList<MethodDoc>();
        for (ClassDoc c : root.classes()) {
            for(MethodDoc m : c.methods()) {
                if (isTest(m))
                    result.add(m);
            }
        }
        return result.toArray(new MethodDoc[0]);
    }
    
    // simplified test detection
    private static boolean isTest(MethodDoc m) {
        for(AnnotationDesc a: m.annotations()) {
            if (a.annotationType().name().equals("Test"))
                return true;
        }
        return false;
    }
    

    然后,对于每个测试,我检索组集:

    static Set<String> getMethodGroups(MethodDoc m) {
        Set<String> result = getGroups(m);
        result.addAll(getGroups(m.containingClass()));
        return result;
    }
    
    static Set<String> getGroups(ProgramElementDoc m) {
        Set<String> result = new HashSet<String>();
        for(AnnotationDesc a: m.annotations()) {
            if (a.annotationType().name().equals("Test")) {
                for(ElementValuePair ev : a.elementValues()) {
                    if (ev.element().name().equals("groups")) {
                        String value = ev.value().toString();
                        StringTokenizer tokenizer = new StringTokenizer(value, "{}\", ");
                        while (tokenizer.hasMoreElements()) {
                            result.add(tokenizer.nextToken());
                        }
                    }
                }
            }
        }
        return result;
    }
    

    剩下的只是标准的doclet处理。此外,我发现我可以在javadoc中直接使用自定义标记,例如

    /**
     * Some description
     * @Step Step 1
     * @Step Step 2
    */
    void someMethod() {}