JUnit4.8.2源代码分析-3.1 Description-测试树

来源:互联网 发布:ubuntu gnome3 编辑:程序博客网 时间:2024/06/08 20:09

重新把org.junit.runner.Description的源代码读了一下,结合成组测试(Suite)了解Description所表示的测试树

Description使用组合模式描述一个测试的信息。所有元素都是Composite对象

例如myTest.units包中有Unit1、Unit2、Unit3,而SuiteUnit将Unit2、Unit3和myTest.param.ParametTestUnit组成一组。

    public static void tree(){        Request rqst = Request.classes(Unit1.class,SuiteUnit.class);        Runner r=rqst.getRunner();        Description descr = r.getDescription();        String prefix = "";        print(descr,prefix);                pln( "the total number of atomic tests = "+descr.testCount() );//the total number of atomic tests.    }    public static void print(Description now,String prefix){         pln(prefix+ now.getDisplayName() );                if(now.isSuite()) {            prefix+="  ";            for (Description x : now.getChildren()){                                print(x,prefix);            }        }    }    
运行tree()的输出为:

null
  myTest.units.Unit1
    m1(myTest.units.Unit1)
    m2(myTest.units.Unit1)
  myTest.units.SuiteUnit
    myTest.units.Unit2
      test2(myTest.units.Unit2)
    myTest.units.Unit3
      testSth(myTest.units.Unit3)
    myTest.param.ParametTestUnit
      [0]
        testOdd[0](myTest.param.ParametTestUnit)
      [1]
        testOdd[1](myTest.param.ParametTestUnit)
      [2]
        testOdd[2](myTest.param.ParametTestUnit)
      [3]
        testOdd[3](myTest.param.ParametTestUnit)
      [4]
        testOdd[4](myTest.param.ParametTestUnit)
      [5]
        testOdd[5](myTest.param.ParametTestUnit)
the total number of atomic tests = 10


测试树的叶子,是this. getChildren().size()为0的结点。isTest()(是否叶子)返回true。Description的两个命名常量EMPTY(名字为"NoTests")和TEST_MECHANISM(名字为"Test mechanism")是特殊的叶子。但它通常表示一个被测试的方法(atomic/ a single test),或一个@test。包含的信息有:

       privatefinal ArrayList<Description> fChildren= newArrayList<Description>(); //无元素

       privatefinal String fDisplayName;      

       privatefinal Annotation[] fAnnotations;

测试树的一般元素/Composite,用fChildren保存其子结点。如一个单元测试类的Description,子结点包括所有@test修饰的方法;而一个Suite的子结点包括几个单元测试类的Description,而单元测试类和成组测试类又可以构成更大的Composite。

注意:单元测试类Description的子结点不包括@Before等修饰的方法。

相关方法:

String getDisplayName():返回fDisplayName。本描述的用于打印的名字,一般情况下都常用类全名或JUnit的方法字符串如method(所属类的全名)

String getClassName()、String getMethodName():解析方法字符串,获得@test修饰的方法相关的类全名和方法名;Class<?> getTestClass(),由getClassName()的返回值为参数name调用Class.forName(name);

 

ArrayList<Description> getChildren():返回fChildren。

void addChild(Description description)

isTest()(是否叶子)、isSuite()(是否组合):互斥的一对判断

isEmpty()

 

Collection<Annotation> getAnnotations():将fAnnotations数组形式的转换为Collection;本Description所对应元素前使用的标注;

<T extends Annotation> TgetAnnotation(Class<T> annotationType)。fAnnotations中是否含有。

 

@Override hashCode()、equals(Object obj)、toString();

 

组合模式中的Operation()的对应物为int testCount(),包含的叶子测试的总数。

Description有一个私有构造器,而提供了静态方法获得Description对象。

Description childlessCopy(),不知道其意图。


1 0
原创粉丝点击