天天看点

深入JUnit源码之Rule 深入JUnit源码之Rule

初次用文字的方式记录读源码的过程,不知道怎么写,感觉有点贴代码的嫌疑。不过中间还是加入了一些自己的理解和心得,希望以后能够慢慢的改进,感兴趣的童鞋凑合着看吧,感觉junit这个框架还是值得看的,里面有许多不错的设计思想在,更何况它是kent beck和erich gamma这样的大师写的。。。。。

junit中的rule是对@beforeclass、@afterclass、@before、@after等注解的另一种实现,其中@classrule实现的功能和@beforeclass、@afterclass类似;@rule实现的功能和@before、@after类似。junit引入@classrule和@rule注解的关键是想让以前在@beforeclass、@afterclass、@before、@after中的逻辑能更加方便的实现重用,因为@beforeclass、@afterclass、@before、@after是将逻辑封装在一个测试类的方法中的,如果实现重用,需要自己将这些逻辑提取到一个单独的类中,再在这些方法中调用,而@classrule、@rule则是将逻辑封装在一个类中,当需要使用时,直接赋值即可,对不需要重用的逻辑则可用匿名类实现,也因此,junit在接下来的版本中更倾向于多用@classrule和@rule,虽然就我自己来说,感觉还是用@beforeclass、@afterclass、@before、@after这些注解更加熟悉一些,也可能是我测试代码写的还不够多的原因吧l。同时由于statement链构造的特殊性@classrule或@rule也保证了类似父类@beforeclass或@before注解的方法要比子类的注解方法执行早,而父类的@afterclass或@after注解的方法执行要比子类要早的特点。

@classrule和@rule只能注解在字段中,并且该字段的类型必须实现了testrule接口,对@classrule注解的字段还必须是public,static,并且@classrule注解的字段在运行时不可以抛异常,不然junit的行为是未定义的,这个是注释文档中这样描述的,实际情况则一般是直接触发testfailure事件,至于其他结果,则要看不同的testrule实现不同,这个特征将在下面详细讲解;而对@rule注解的字段必须是public,非static,关于@classrule注解字段和@rule注解字段的验证是在rulefieldvalidator中做的(具体可以参考runner小节):

 1 public enum rulefieldvalidator {

 2     class_rule_validator(classrule.class, true), rule_validator(rule.class, false);

 3     

深入JUnit源码之Rule 深入JUnit源码之Rule

 4     public void validate(testclass target, list<throwable> errors) {

 5        list<frameworkfield> fields= target.getannotatedfields(fannotation);

 6        for (frameworkfield each : fields)

 7            validatefield(each, errors);

 8     }

 9     private void validatefield(frameworkfield field, list<throwable> errors) {

10        optionallyvalidatestatic(field, errors);

11        validatepublic(field, errors);

12        validatetestruleormethodrule(field, errors);

13     }

14     private void optionallyvalidatestatic(frameworkfield field,

15            list<throwable> errors) {

16        if (fonlystaticfields && !field.isstatic())

17            adderror(errors, field, "must be static.");

18     }

19     private void validatepublic(frameworkfield field, list<throwable> errors) {

20        if (!field.ispublic())

21            adderror(errors, field, "must be public.");

22     }

23     private void validatetestruleormethodrule(frameworkfield field,

24            list<throwable> errors) {

25        if (!ismethodrule(field) && !istestrule(field))

26            adderror(errors, field, "must implement methodrule or testrule.");

27     }

28     private boolean istestrule(frameworkfield target) {

29        return testrule.class.isassignablefrom(target.gettype());

30     }

31     private boolean ismethodrule(frameworkfield target) {

32        return org.junit.rules.methodrule.class.isassignablefrom(target

33               .gettype());

34     }

35     private void adderror(list<throwable> errors, frameworkfield field,

36            string suffix) {

37        string message= "the @" + fannotation.getsimplename() + " '"

38               + field.getname() + "' " + suffix;

39        errors.add(new exception(message));

40     }

41 }

本节将重点介绍当前junit默认实现的几个testrule,先给出类图,然后介绍源码实现以及用途,最后还将简单的介绍runrules这个statement的运行信息,虽然这个类非常简单,在statement那节中也已经简单的做过介绍了。

在学一个新的框架的时候,我一直比较喜欢先看一下框架的类图,这样自己总体上就有个概念了。这里也先给一张junit中testrule的类图吧:

深入JUnit源码之Rule 深入JUnit源码之Rule

testrule的类结构图还是比较简单的,只是将它置于junit的statement框架中,有些问题分析起来就比较复杂了。为了保持问题的简单,我们先来看一下每个单独的类各自实现了什么功能和怎么实现吧。

先来看两个简单的吧,testwatcher为子类提供了四个事件方法以监控测试方法在运行过程中的状态,一般它可以作为信息记录使用。如果testwatcher作为@classrule注解字段,则该测试类在运行之前(调用所有的@beforeclass注解方法之前)会调用starting()方法;当所有@afterclass注解方法调用结束后,succeeded()方法会被调用;若@afterclass注解方法中出现异常,则failed()方法会被调用;最后,finished()方法会被调用;所有这些方法的description是runner对应的description。如果testwatcher作为@rule注解字段,则在每个测试方法运行前(所有的@before注解方法运行前)会调用starting()方法;当所有@after注解方法调用结束后,succeeded()方法会被调用;若@after注解方法中跑出异常,则failed()方法会被调用;最后,finished()方法会被调用;所有description的实例是测试方法的description实例。

testname是对testwatcher的一个简单实现,它会在starting()方法中记录每次运行的名字。如果testname作为@rule注解字段,则starting()中传入的description是对每个测试方法的description,因而getmethodname()方法返回的是测试方法的名字。一般testname不作为@classrule注解字段,如果真有人这样用了,则starting()中description的参数是runner的description实例,一般getmethodname()返回值为null。

 1 public abstract class testwatcher implements testrule {

 2     public statement apply(final statement base, final description description) {

 3        return new statement() {

 4            @override

 5            public void evaluate() throws throwable {

 6               starting(description);

 7               try {

 8                   base.evaluate();

 9                   succeeded(description);

10               } catch (assumptionviolatedexception e) {

11                   throw e;

12               } catch (throwable t) {

13                   failed(t, description);

14                   throw t;

15               } finally {

16                   finished(description);

17               }

18            }

19        };

20     }

21     protected void succeeded(description description) {

23     protected void failed(throwable e, description description) {

24     }

25     protected void starting(description description) {

26     }

27     protected void finished(description description) {

28     }

29 }

30 public class testname extends testwatcher {

31     private string fname;

32     @override

33     protected void starting(description d) {

34        fname= d.getmethodname();

35     }

36     public string getmethodname() {

37        return fname;

38     }

39 }

temporaryfolder是对externalresource的一个实现,它在before()方法中在临时文件夹中创建一个随机的文件夹,以junit开头;并在after()方法将创建的临时文件夹清空,并删除该临时文件夹。另外temporaryfolder还提供了几个方法以在新创建的临时文件夹中创建新的文件、文件夹。

 1 public abstract class externalresource implements testrule {

 2     public statement apply(statement base, description description) {

 3        return statement(base);

 4     }

 5     private statement statement(final statement base) {

 6        return new statement() {

 7            @override

 8            public void evaluate() throws throwable {

 9               before();

10               try {

11                   base.evaluate();

12               } finally {

13                   after();

14               }

15            }

16        };

17     }

18     protected void before() throws throwable {

19     }

20     protected void after() {

21     }

22 }

23 public class temporaryfolder extends externalresource {

24     private file folder;

25     @override

26     protected void before() throws throwable {

27        create();

29     @override

30     protected void after() {

31        delete();

32     }

33     public void create() throws ioexception {

34        folder= newfolder();

36     public file newfile(string filename) throws ioexception {

37        file file= new file(getroot(), filename);

38        file.createnewfile();

39        return file;

41     public file newfile() throws ioexception {

42        return file.createtempfile("junit", null, folder);

43     }

44     public file newfolder(string

深入JUnit源码之Rule 深入JUnit源码之Rule

 foldernames) {

45        file file = getroot();

46        for (string foldername : foldernames) {

47            file = new file(file, foldername);

48            file.mkdir();

49        }

50        return file;

51     }

52     public file newfolder() throws ioexception {

53        file createdfolder= file.createtempfile("junit", "", folder);

54        createdfolder.delete();

55        createdfolder.mkdir();

56        return createdfolder;

57     }

58     public file getroot() {

59        if (folder == null) {

60            throw new illegalstateexception("the temporary folder has not yet been created");

61        }

62        return folder;

63     }

64     public void delete() {

65        recursivedelete(folder);

66     }

67     private void recursivedelete(file file) {

68        file[] files= file.listfiles();

69        if (files != null)

70            for (file each : files)

71               recursivedelete(each);

72        file.delete();

73     }

74 }

verifier是在所有测试已经结束的时候,再加入一些额外的逻辑,如果额外的逻辑通过,才表示测试成功,否则,测试依旧失败,即使在之前的运行中都是成功的。verify可以为一些很多测试方法加入一些公共的验证逻辑。当verifier应用在@rule注解字段中,它在所偶@after注解方法运行完后,会调用verify()方法,如果verifier()方法验证失败抛出异常,则该测试方法的testfailure事件将会被触发,导致该测试方法失败;当verifier应用在@classrule时,它在所有的@afterclass注解的方法执行完后,会执行verify()方法,如果verify失败抛出异常,将会触发关于该测试类的testfailure,此时测试类中的所有测试方法都已经运行成功了,却在最后收到一个关于测试类的testfailure事件,这确实是一个比较诡异的事情,因而@classrule中提到errorcollector(verifier)不可以用在@classrule注解中,否则其行为为定义;更一般的@classrule注解的字段运行时不能抛异常,不然其行为是未定义的。

errorcollector是对verifier的一个实现,它可以在运行测试方法的过程中收集错误信息,而这些错误信息知道最后调用errorcollector的verify()方法时再处理。其实就目前来看,我很难想象这个需求存在的意义,因为即使它将所有的错误信息收集在一起了,在事件发布是,它还是会为每个错误发布一次testfailure事件(参考eachtestnotifier的实现),除非有一种需求是即使测试方法在运行过程的某个点运行出错,也只是先记录这个错误,等到所有逻辑运行结束后才去将这个测试方法运行过程中存在的错误发布出去,这样一次运行就可以知道测试代码中存在出错的地方。errorcollector中还提供了几个收集错误的方法:如adderror()、checkthat()、checksucceeds()等。这里的checkthat()方法用到了hamcrest框架中的matcher,这部分的内容将在assert小节中详细介绍。

 1 public class verifier implements testrule {

 2     public statement apply(final statement base, description description) {

 6               base.evaluate();

 7               verify();

 8            }

 9        };

10     }

11     protected void verify() throws throwable {

12     }

13 }

14 public class errorcollector extends verifier {

15     private list<throwable> errors= new arraylist<throwable>();

16     @override

17     protected void verify() throws throwable {

18        multiplefailureexception.assertempty(errors);

20     public void adderror(throwable error) {

21        errors.add(error);

23     public <t> void checkthat(final t value, final matcher<t> matcher) {

24        checkthat("", value, matcher);

25     }

26     public <t> void checkthat(final string reason, final t value, final matcher<t> matcher) {

27        checksucceeds(new callable<object>() {

28            public object call() throws exception {

29               assertthat(reason, value, matcher);

30               return value;

31            }

32        });

33     }

34     public object checksucceeds(callable<object> callable) {

35        try {

36            return callable.call();

37        } catch (throwable e) {

38            adderror(e);

39            return null;

40        }

41     }

42 }

 1 public class timeout implements testrule {

 2     private final int fmillis;

 3     public timeout(int millis) {

 4        fmillis= millis;

 5     }

 6     public statement apply(statement base, description description) {

 7        return new failontimeout(base, fmillis);

 9 }

10 public class expectedexception implements testrule {

11     public static expectedexception none() {

12        return new expectedexception();

14     private matcher<object> fmatcher= null;

15     private expectedexception() {

16     }

17     public statement apply(statement base,

18            org.junit.runner.description description) {

19        return new expectedexceptionstatement(base);

21     public void expect(matcher<?> matcher) {

22        if (fmatcher == null)

23            fmatcher= (matcher<object>) matcher;

24        else

25            fmatcher= both(fmatcher).and(matcher);

27     public void expect(class<? extends throwable> type) {

28        expect(instanceof(type));

29     }

30     public void expectmessage(string substring) {

31        expectmessage(containsstring(substring));

33     public void expectmessage(matcher<string> matcher) {

34        expect(hasmessage(matcher));

36     private class expectedexceptionstatement extends statement {

37        private final statement fnext;

38        public expectedexceptionstatement(statement base) {

39            fnext= base;

41        @override

42        public void evaluate() throws throwable {

43            try {

44               fnext.evaluate();

45            } catch (throwable e) {

46               if (fmatcher == null)

47                   throw e;

48               assert.assertthat(e, fmatcher);

49               return;

50            }

51            if (fmatcher != null)

52               throw new assertionerror("expected test to throw "

53                      + stringdescription.tostring(fmatcher));

54        }

55     }

56     private matcher<throwable> hasmessage(final matcher<string> matcher) {

57        return new typesafematcher<throwable>() {

58            public void describeto(description description) {

59               description.appendtext("exception with message ");

60               description.appenddescriptionof(matcher);

61            }

62            @override

63            public boolean matchessafely(throwable item) {

64               return matcher.matches(item.getmessage());

65            }

66        };

67     }

68 }

rulechain提供一种将多个testrule串在一起执行的机制,它首先从outchain()方法开始创建一个最外层的testrule创建的statement,而后调用round()方法,不断向内层添加testrule创建的statement。如其注释文档中给出的一个例子:

1 @rule

2 public testrule chain= rulechain

3                     .outerrule(new loggingrule("outer rule"))

4                     .around(new loggingrule("middle rule"))

5                     .around(new loggingrule("inner rule"));

如果loggingrule只是类似externalresource中的实现,并且在before()方法中打印starting…,在after()方法中打印finished…,那么这条链的执行结果为:

starting outer rule

starting middle rule

starting inner rule

finished inner rule

finished middle rule

finished outer rule

由于testrule的apply()方法是根据的当前传入的statement,创建一个新的statement,以决定当前testrule逻辑的执行位置,因而第一个调用apply()的testrule产生的statement将在statement链的最里面,也正是有这样的逻辑,所以around()方法实现的时候,都是把新加入的testrule放在第一个位置,然后才保持其他已存在的testrule位置不变。

 1 public class rulechain implements testrule {

 2     private static final rulechain empty_chain= new rulechain(

 3            collections.<testrule> emptylist());

 4     private list<testrule> rulesstartingwithinnermost;

 5     public static rulechain emptyrulechain() {

 6        return empty_chain;

 7     }

 8     public static rulechain outerrule(testrule outerrule) {

 9        return emptyrulechain().around(outerrule);

11     private rulechain(list<testrule> rules) {

12        this.rulesstartingwithinnermost= rules;

14     public rulechain around(testrule enclosedrule) {

15        list<testrule> rulesofnewchain= new arraylist<testrule>();

16        rulesofnewchain.add(enclosedrule);

17        rulesofnewchain.addall(rulesstartingwithinnermost);

18        return new rulechain(rulesofnewchain);

20     public statement apply(statement base, description description) {

21        for (testrule each : rulesstartingwithinnermost)

22            base= each.apply(base, description);

23        return base;

25 }

testrule实例的运行都是被封装在一个叫runrules的statement中运行的。在构造runrules实例是,传入testrule实例的集合,然后遍历所有的testrule实例,为每个testrule实例调用一遍apply()方法以构造出要执行testrule的statement链。类似上小节的rulechain,这里在前面的testrule构造的statement被是最终构造出的statement的最里层,结合testclass在获取注解字段的顺序时,先查找子类,再查找父类,因而子类的testrule实例产生的statement是在statement链的最里层,从而保证了类似externalresource实现中,before()方法的执行父类要比子类要早,而after()方法的执行子类要比父类要早的特性。

 1 public class runrules extends statement {

 2     private final statement statement;

 3     public runrules(statement base, iterable<testrule> rules, description description) {

 4        statement= applyall(base, rules, description);

 6     @override

 7     public void evaluate() throws throwable {

 8        statement.evaluate();

 9     }

10     private static statement applyall(statement result, iterable<testrule> rules,

11            description description) {

12        for (testrule each : rules)

13            result= each.apply(result, description);

14        return result;

15     }

16 }