初次用文字的方式记录读源码的过程,不知道怎么写,感觉有点贴代码的嫌疑。不过中间还是加入了一些自己的理解和心得,希望以后能够慢慢的改进,感兴趣的童鞋凑合着看吧,感觉junit这个框架还是值得看的,里面有许多不错的设计思想在,更何况它是kent beck和erich gamma这样的大师写的。。。。。
不知道是因为第一份工作的影响还是受在博客园上看到的那句“源代码里没有秘密”的影响,总之,近来对很多框架的源码都很感兴趣,拿到一个都想看看。其实自从学习java以来也看过不少了,从刚开始接触的tomcat,到struts2,再到入职当前这份工作后看的log4j,commons validator和springbatch,可惜除了commons validator的源码都看完了,其他的框架源码都半途而废了,并且commons validator看完后,也没有什么记录下来,所以基本上都可以忽略,其实当时也知道看完要有总结和记录才会有真正的收获,然而还是因为各种事情而没有做。所以这次看junit,发奋看完后一定要做总结,并记录。
对于junit,一直以为很简单,可以很快的看完,就当练练手,然而当我真正看完后,才发现junit其实并不简单,内部框架提供了很多特性,平时都没用过,而且也没见过,比如使用runwith注解以指定特定的runner、rule、使用hamcrest框架的assert.assertthat()方法等。其实junit提供的这些特性在一些特殊场合很有用处,然而对于单元测试,很多人却因为太忙或者因为嫌烦,维护麻烦等各种理由而尽量避免。我也是一样,虽然我一直承认单元测试非常重要,它不仅仅可以在前期影响设计、而且可以为后期的一些重构或者bug修复提供信心,但是要我真正的认真的为一个模块写单元测试,也感觉有点厌烦,再加上当前项目又是一个很少写单元测试的环境,对这方面坚持就松懈了。
后来,想系统的看一下项目的源码,可是代码量太多,也没有比较明确的模块分工,没有比较完善的单元测试,再加上当前项目主要是基于文件对数据的处理,没有看到数据流,只是看代码的话,感觉晕头转向的,所以就想着补一些单元测试以使自己可以更好的理解项目代码。问题是项目是跑在linux server上的,项目在开发的过程中没有完全考虑支持跨平台,同时有些操作内存消耗也很大,所以并不是所有的代码都可以在本地跑,等等,总之各种原因吧,我开始打算写一个可以在linux下用跑测试代码的工具。然后悲剧的发现除了会使用eclipse中的junit,其实我对junit一无所知。所以有些时候工具虽然能提供我们方便,但是它也隐藏了内部细节,最后我们自以为已经很了解某些东西了,其实离开了工具,我们一无所知。
最后加个注释,这篇文章所有的代码是基于junit4.10的,今天我发现这个版本和之前的版本(junit4.4)的代码还是有比较大的差别的。本系列最后可能会涉及到一点和junit之前版本相关的信息,不过这个就要看有没有这个时间了。l
runner是junit的核心,它封装了一个测试类中所有的测试方法,如blockjunit4classrunner,或者是多个runner,如suite;在运行过程中,遍历并运行所有测试方法(可以通过filter和sorter控制是否要执行某些测试方法以及执行测试方法的顺序)。
在使用junit时,可能最常用的几个注解就是@beforeclass、@afterclass、@before、@after、@test、@ignore了,这几个注解所表达的意思相信很多人都很熟悉了,并且从它们的名字中也可以略知一二。这几个注解,除了@test标记了哪个方法为测试方法,该方法必须为public,无返回,不带参;@ignore标明某个方法即使有@test的注解,也会忽略不运行,如junit文档中解释,在某些情况下,我们可能想临时的不想执行某些测试方法,除了将该测试方法整个注释掉,junit为我们提供了@ignore注解,此时即使某方法包含@test注解,该方法也不会作为测试方法执行,@ignore还可以注解在类上,当一个类存在@ignore注解时,该类所有的方法都不会被认为是测试方法;而剩下的四个注解则是junit为在测试类运行时的不同切面提供了切入点,如@beforeclass和@afterclass注解分别在测试类运行时前后各提供了一个切入点,这两个注解必须使用在public,静态,无返回,不带参的方法中,可以为每种注解指定多个方法,多个方法的执行顺序依赖与java的反射机制,因而对一种注解的多个方法,在实际中不应该存在顺序依赖,为一种注解写多个方法的情况应该很少;而@before和@after注解则是在每个测试方法的运行前后各提供了一个切入点,这两个注解必须使用在public,无返回,不带参的方法中。同@beforeclass和@afterclass,同一种注解可以注释多个方法,他们的执行顺序也依赖于反射机制,因而不能对顺序有依赖。更直观的,如下图所示。
加点不完全相关的,这事实上是一种aop思想的实现。自从知道aop后,一直很喜欢这个想法,它事实上也是一种分层的思想。一个request从一个管道流进,经过层层处理后从另一个管道流出,在管道的流动过程中,每一层都对自己实现的功能做一些处理,如安全验证、运行时间记录、进入管道后打开某个链接出去之前关闭该链接、异常记录等等相对独立的功能都可以抽取出来到一个层中,从而在实际编码业务逻辑过程中可以专注于业务,而不用管这些不怎么相关但有必须有的逻辑,不仅是代码的模块分层更加清晰,减轻程序员的负担,还提高了程序的安全性,因为这样就可以部分避免有些事情必须要做容易忘了尴尬。aop的思想最出名的应该是spring中提供的支持了,但是我个人更喜欢struts2通过interceptor提供的aop实现,这是题外话。
为了更加清晰的了解junit的一些行为,我们先来看一下如下的一个测试例子:
1 public class corejunit4sampletest {
2 @beforeclass
3 public static void beforeclass() {
4 system.out.println("beforeclass() method executed.");
5 system.out.println();
6 }
7 @beforeclass
8 public static void beforeclass2() {
9 system.out.println("beforeclass2() method executed.");
10 system.out.println();
11 }
12 @afterclass
13 public static void afterclass() {
14 system.out.println("afterclass() method executed.");
15 system.out.println();
16 }
17 @before
18 public void before() {
19 system.out.println("before() method executed.");
20 }
21 @after
22 public void after() {
23 system.out.println("after() method executed");
24 }
25 @test
26 public void testsucceeded() {
27 system.out.println("testsucceeded() method executed.");
28 }
29 @test
30 @ignore
31 public void testignore() {
32 system.out.println("testignore() method executed.");
33 }
34 @test
35 public void testfailed() {
36 system.out.println("testfailed() method executed.");
37 throw new runtimeexception("throw delibrately
");
38 }
39 @test
40 public void testassumptionfailed() {
41 system.out.println("testassumptionfailed() method executed.");
42 assume.assumethat(0, is.is(1));
43 }
44 @test
45 public void testfilteredout() {
46 system.out.println("testfilteredout() method executed.");
47 }
48 }
这个是一个简单的测试类,内部实现基本上只是打印,以确定测试方法的运行位置。该测试方法包括两个@beforeclass注解的方法,以测试多个@beforeclass注解时他们的运行顺序问题;@afterclass、@before、@after注解的方法各一个,以测试他们的运行位置问题;在多个@test注解的测试方法中,testsucceeded()测试方法用于测试通过时runlinstener的运行结果,testignore()测试方法测试@ignore注解对测试结果的影响,testfailed()方法测试在测试方法抛异常时runlistener的运行结果,testassumptionfailed()方法测试在测试方法断言出错时runlistener的运行结果,testfilteredout()方法测试filter的功能。在junit中,blockjunitclassrunner是其最核心的runner,它对一个只包含测试方法的测试类的运行做了封装,并且它还实现了filterable和sortable的接口,因而支持filter和sorter,为了更全面的展现junit提供的功能,我在这个例子中还加入了filter和sorter的测试,其中实现了一个filter类:methodnamefilter,在构造时指定要过滤掉的方法名,runner在运行之前调用filter()方法,以过滤掉这些方法。对于sorter只实现了一个按字母序排列的comparator,它会以参数形式传递给sorter构造函数,以决定测试方法的顺序,runner在运行之前调用sort()方法,以按指定的顺序排列测试方法:
1 public class methodnamefilter extends filter {
2 private final set<string> excludedmethods = new hashset<string>();
3 public methodnamefilter(string
excludedmethods) {
4 for(string method : excludedmethods) {
5 this.excludedmethods.add(method);
6 }
7 }
8 @override
9 public boolean shouldrun(description description) {
10 string methodname = description.getmethodname();
11 if(excludedmethods.contains(methodname)) {
12 return false;
13 }
14 return true;
15 }
16 @override
17 public string describe() {
18 return this.getclass().getsimplename() + "-excluded methods: " +
19 excludedmethods;
21 }
22 public class alphabetcomparator implements comparator<description> {
23 @override
24 public int compare(description desc1, description desc2) {
25 return desc1.getmethodname().compareto(desc2.getmethodname());
26 }
27 }
由于本文主要讲解junit中的runner的实现,因而在这个例子中,我将直接构造blockjunit4classrunner实例,以运行上述的测试类:
1 public class blockjunit4classrunnerexecutor {
2 public static void main(string[] args) {
3 runnotifier notifier = new runnotifier();
4 result result = new result();
5 notifier.addfirstlistener(result.createlistener());
6 notifier.addlistener(new logrunlistener());
7
8 runner runner = null;
9 try {
10 runner = new blockjunit4classrunner(corejunit4sampletest.class);
11 try {
12 ((blockjunit4classrunner)runner).filter(new methodnamefilter("testfilteredout"));
13 } catch (notestsremainexception e) {
14 system.out.println("all methods are been filtered out");
15 return;
16 }
17 ((blockjunit4classrunner)runner).sort(new sorter(new alphabetcomparator()));
18 } catch (throwable e) {
19 runner = new errorreportingrunner(corejunit4sampletest.class, e);
20 }
21 notifier.firetestrunstarted(runner.getdescription());
22 runner.run(notifier);
23 notifier.firetestrunfinished(result);
25 }
junit会在runner运行之前通过runnotifier发布testrunstarted事件表示junit运行开始,并在runner运行结束之后通过runnotifier发布testrunfinished时间,表示junit运行结束。在runner运行过程中,在每个测试方法开始前也会通过runnotifier发布teststarted事件,在测试方法结束后发布testfinished事件(不管该测试方法通过还是未通过),若测试失败,则发布testfailure事件,若测试方法因调用assume类中的方法失败(这种失败不认为是测试失败),则会发布testassumptionfailure事件,若遇到一个ignore测试方法,发布testignored事件。我们可以再runnotifier中加入要注册的listener(事件接收器),如上例所示,为了测试,这个例子编写的logrunlistener代码如下:
1 public class logrunlistener extends runlistener {
2 public void testrunstarted(description description) throws exception {
4 println("==>junit4 started with description: \n" + description);
5 println();
7 public void testrunfinished(result result) throws exception {
8 println("==>junit4 finished with result: \n" + describe(result));
9 }
10 public void teststarted(description description) throws exception{
11 println("==>test method started with description: " + description);
13 }
14 public void testfinished(description description) throws exception {
16 println("==>test method finished with description: " + description);
18 println();
19 }
20 public void testfailure(failure failure) throws exception {
21 println("==>test method failed with failure: " + failure);
22 }
23 public void testassumptionfailure(failure failure) {
24 println("==>test method assumption failed with failure: " + failure);
27 public void testignored(description description) throws exception {
28 println("==>test method ignored with description: " + description);
30 println();
31 }
32 private string describe(result result) {
33 stringbuilder builder = new stringbuilder();
34 builder.append("\tfailurecount: " + result.getfailurecount())
35 .append("\n");
36 builder.append("\tignorecount: " + result.getignorecount())
37 .append("\n");
38 builder.append("\truncount: " + result.getruncount())
39 .append("\n");;
40 builder.append("\truntime: " + result.getruntime())
41 .append("\n");
42 builder.append("\tfailures: " + result.getfailures())
43 .append("\n");;
44 return builder.tostring();
45 }
46 private void println() {
47 system.out.println();
48 }
49 private void println(string content) {
50 system.out.println(content);
51 }
52 }
最后这个例子的运行结果(从上面的分析中,这个运行结果应该已经很清晰了,只是有两点需要注意,其一,@ignore注解的方法会被忽略不执行,包括@before、@after注解的方法,也不会触发该teststarted事件,但是在result会记录被忽略的测试方法数,而被filter过滤掉的方法(testfilteredout())则不会有任何记录;其二,事件的触发都是在@before注解之前或@after注解之后,事实上,如果测试方法中包含rule字段的话,也会在rule执行之前或之后,这就是junit抽象出的statement提供的特性,这是一个非常好的设计,这个特性将会在下一节:深入junit源码之statement中讲解):
==>junit4 started with description:
levin.blog.junit.sample.simple.corejunit4sampletest
beforeclass2() method executed.
beforeclass() method executed.
==>test method started with description: testassumptionfailed(levin.blog.junit.sample.simple.corejunit4sampletest)
before() method executed.
testassumptionfailed() method executed.
after() method executed
==>test method assumption failed with failure: testassumptionfailed(levin.blog.junit.sample.simple.corejunit4sampletest): got: <0>, expected: is <1>
==>test method finished with description: testassumptionfailed(levin.blog.junit.sample.simple.corejunit4sampletest)
==>test method started with description: testfailed(levin.blog.junit.sample.simple.corejunit4sampletest)
testfailed() method executed.
==>test method failed with failure: testfailed(levin.blog.junit.sample.simple.corejunit4sampletest): throw delibrately
==>test method finished with description: testfailed(levin.blog.junit.sample.simple.corejunit4sampletest)
==>test method ignored with description: testignore(levin.blog.junit.sample.simple.corejunit4sampletest)
==>test method started with description: testsucceeded(levin.blog.junit.sample.simple.corejunit4sampletest)
testsucceeded() method executed.
==>test method finished with description: testsucceeded(levin.blog.junit.sample.simple.corejunit4sampletest)
afterclass() method executed.
==>junit4 finished with result:
failurecount: 1
ignorecount: 1
runcount: 3
runtime: 36
failures: [testfailed(levin.blog.junit.sample.simple.corejunit4sampletest): throw delibrately
]
从上面这个例子中,我们已经知道junit的核心功能以及不同注解方法执行的顺序问题,然而既然本文是关注内部源码的,因而接下来就要讨论如何实现上述的这些功能。
所谓面向对象中的类即是对某些事物或行为进行抽象和封装,从而实现某些功能,一个类可以看成是一个模块,它一般包含数据和行为,并提供给外界一定的接口,多个类之间通过各自的接口与外界交互,从而形成一个大的系统,有点类似分治的算法。在分治算法中最重要的是找到正确的方法以将问题划分成各个区间,并最后使用一定的规则将各个区间解决的问题连结在一起,以解决整个系统的问题。在面向对象中同样要找到一个正确的方法将系统的问题划分成各个小模块,用类来封装,并定义类的接口以使各个类之间可以交互连结以形成一个大的系统。在实现中,我们也经常遇到某些事物是不同的,但是他们有一些共同的属性或行为,在面向对象中对这个情况的处理是将相同的属性或行为抽象成一个父类,而由各自的子类继承父类提供各自不同的属性和行为。然而有些时候,某些事物他们都具有某种行为,但是这些行为的结果却是不同的,对这种情况,面向对象则采用多态的方式支持这种需求,即在父类中定义行为,在子类中重写行为。在面向对象设计中,如何设计系统的类结构,包括类的继承结构、类之间的交互接口等问题了是面向对象设计的核心问题。
junit将测试类中的方法(测试方法以及切面方法,@beforeclass、@afterclass、@before、@after等注解的方法)抽象成frameworkmethod类模块,和测试相关的字段(由@rule和@classrule注解的字段)抽象成frameworkfield类模块,而这两个类具有一些共同的行为,如获取在其之上的所有注解类、是否被其他相关成员隐藏等,因而junit将这些共同行为提取到父类frameworkmember中。对每个测试类,junit使用testclass类来封装,testclass类以测试类的class实例为构造函数的参数,它收集测试类中所有junit识别的注解方法(@beforeclass、@afterclass、@before、@after、@test、@ignore)和注解字段(@rule、@classrule),以供其他类查询。在每一次运行中,junit使用runner对其封装,它可以是只包含一个测试类的blockjunit4classrunner,也可以是包含多个runner的suite(这有点类似composite设计模式,以测试方法为叶子节点,以runner为包含叶子节点的节点将依次junit运行过程中的所有测试方法组成一棵树);这两个runner都继承自parentrunner。parentrunner表达它是以一个在树中具有子节点的节点,实现了filterable接口和sortable接口,以实现filter和sort的功能,parentrunner继承自runner。runner是一个更高层次的抽象,目前在junit4中表达该runner只是在执行树中的没有子节点的runner节点,如errorreportingrunner、ignoredclassrunner等;在junit3中不是采用注解的方式取得测试方法,为了兼容性,junit4中也提供了junit38classrunner类以完成兼容性的工作。runner实现了discribable接口,以表明可以通过description来描述一个runner;description主要是对runner和测试方法的描述,有点类似tostring()的味道。runner的每一次执行过程,如切面方法的执行、测试方法的执行、rule字段的执行等,junit都将其封装在statement类中,一个测试方法的执行可能存在多个statement,他们形成链结构,这是一个我个人非常喜欢的设计,就像servlet中的filter、struts2的interceptor的设计类似,也是对aop的主要实现,这个内容将在另一节中介绍。runner在每个测试方法执行过程中都会通过runnotifier类发布一些事件,如测试方法执行开始、结束、出错、忽略等事件,runnotifier是runner对所有事件处理的封装,我们可以通过它注册runlistener的事件响应类,如上例的logrunlistener的注册。到这里,我们基本上已经介绍完了junit的所有的核心类简单的功能和一些简单的交互,那么我们来看一下他们的类结构图吧:
description类和discribable接口的实现
看完类结构图,那么我们再来看一下源码吧。由于description在junit中应用广泛,又是相对独立于功能的,因而将从description开始:
如上文所说,description是junit中对runner和测试方法的描述,它包含三个字段:
1 private final arraylist<description> fchildren;
2 private final string fdisplayname;
3 private final annotation[] fannotations;
displayname对测试方法的格式为:<methodname>(<classname>),如:
testfailed(levin.blog.junit.sample.simple.corejunit4sampletest)
对runner来说,displayname一般为runner所封装的测试类,然而对没有根类的suite,该值为”null”。annotations字段为测试方法或测试类上所具有的所有注解类。children对测试方法来说为空,对runner来说,表达runner内部所有的测试方法的description或runner的description。作为junit的用户,除非自定义runner,其他的,我们一般都是通过注册自己的runlistener来实现自己想要的统计和信息提示工作,而在listener中并没有直接暴露给我们runner或者是测试类的实例,它是通过提供description实例的方式来获取我们需要的信息。description提供以下的接口供我们使用:
1 public string getdisplayname();
2 public arraylist<description> getchildren();
3 public boolean issuite();
4 public boolean istest();
5 public int testcount();
6 public <t extends annotation> t getannotation(class<t> annotationtype);
7 public collection<annotation> getannotations();
8 public class<?> gettestclass();
9 public string getclassname();
10 public string getmethodname();
runner实现了disacribable接口,该接口只包含一个方法:
1 public interface describable {
2 public abstract description getdescription();
3 }
该方法在parentrunner中创建一个description,并遍历当前runner下的children,并将这些child的description添加到description中最后返回:
1 @override
2 public description getdescription() {
3 description description= description.createsuitedescription(
4 getname(), getrunnerannotations());
5 for (t child : getfilteredchildren())
6 description.addchild(describechild(child));
7 return description;
8 }
9 blockjunit4classrunner:
10 @override
11 protected description describechild(frameworkmethod method) {
12 return description.createtestdescription(
13 gettestclass().getjavaclass(),
14 testname(method), method.getannotations());
15 }
16 suite:
17 @override
18 protected description describechild(runner child) {
19 return child.getdescription();
20 }
21
runlistener是junit提供的自定义对测试运行方法统计的接口,junit用户可以继承runlistener类,在junit运行开始、结束以及每一个测试方法的运行开始、结束、测试失败以及假设出错等情况下加入一些自己的逻辑,如统计整个junit运行的时间(这个在result中已经实现了)、每个运行方法的时间、运行最后有多少方法成功,多少失败等,如上例中的logrunlistener。runlistener定义了如下接口:
1 public class runlistener {
4 }
5 public void testrunfinished(result result) throws exception {
7 public void teststarted(description description) throws exception {
8 }
9 public void testfinished(description description) throws exception {
12 public void testfailure(failure failure) throws exception {
14 public void testassumptionfailure(failure failure) {
16 public void testignored(description description) throws exception {
17 }
18 }
这个类需要注意的是:1. testfinished()不管测试方法是成功还是失败,这个方法总是会被调用;2. 在测试方法中跑出assumptionviolatedexception并不认为是测试失败,一般在测试方法中调用assume类中的方法而失败,会跑该异常,在junit的默认实现中,对这些方法只是简单的忽略,并发布testassumptionfailure()事件,并不认为该方法测试失败,自定义的runner可以改变这个行为;3. 当我们需要自己操作runner实例是,result的信息需要自己手动的注册result中定义的listener,不然result中的信息并不会填写正确,如上例中的做法:
1 result result = new result();
2 notifier.addfirstlistener(result.createlistener());
在实现时,所有事件响应函数提供给我们有三种信息:description、result和failure。其中description已经在上一小节中介绍过了它所具有的信息,这里不再重复。对于result,前段提到过只有它提供的listener后才会取到正确的信息,它包含的信息有:总共执行的测试方法数、忽略的测试方法数、以及所有在测试过程中抛出的异常列表、整个测试过程的执行时间等,result实例在junit运行结束时传入testrunfinished()事件方法中,以帮助我们做一些测试方法执行结果的统计信息,事实上,我感觉这些信息很多时候还是不够的,需要我们在自己的runlistener中自己做一些信息记录。failure类则记录了测试方法在测试失败时抛出的异常以及该测试方法对应的description实例,当在构建runner过程中出现异常,failure也会用于描述测试类,如上例中,如果beforeclass()方法不是静态的话,在初始化runner时就会出错,此时的运行结果如下:
==>test method started with description: initializationerror(levin.blog.junit.sample.simple.corejunit4sampletest)
==>test method failed with failure: initializationerror(levin.blog.junit.sample.simple.corejunit4sampletest): method beforeclass() should be static
==>test method finished with description: initializationerror(levin.blog.junit.sample.simple.corejunit4sampletest)
ignorecount: 0
runcount: 1
runtime: 3
failures: [initializationerror(levin.blog.junit.sample.simple.corejunit4sampletest): method beforeclass() should be static]
runner中的run()方法需要传入runnotifier实例,它是对runlistener的封装,我们可以向其注册多个runlistener,当runner需要发布某个事件时,就会通过它来代理,它则会遍历所有已注册的runlistener,并运行相应的事件。当运行某个runlistener抛异常时,它会首先将这个runlistener移除,并发布测试失败事件,在该事件中的description为一个名为“test mechanism”的description,因为此时是注册的事件处理器失败,无法获知一个description实例:
1 private abstract class safenotifier {
2 void run() {
3 synchronized (flisteners) {
4 for (iterator<runlistener> all= flisteners.iterator();
5 all.hasnext();)
6 try {
7 notifylistener(all.next());
8 } catch (exception e) {
9 all.remove(); // remove the offending listener first to avoid an infinite loop
11 firetestfailure(new failure(
12 description.test_mechanism, e));
13 }
14 }
16 abstract protected void notifylistener(runlistener each) throws exception;
在runnotifier类中还有一个pleasestop()方法从而可以在测试中途停止整个测试过程,其实现时在发布teststarted事件时,如果发现pleasestop字段已经为true,则抛出stoppedbyuserexception,当runner接收到该异常后,将该异常直接抛出。
事实上,parentrunner在发布事件时,并不直接和runnotifier打交道,而是会用eachtestnotifier类对其进行封装,该类只是对multiplefailureexception做了处理,其他只是一个简单的代理。在遇到multiplefailureexception,它会遍历内部每个exception,并对每个exception发布testfailure事件。当在运行@after注解的方法时抛出多个异常类(比如测试方法已经抛出异常了,@after注解方法中又抛出异常或者存在多个@after注解方法,并多个@after注解方法抛出了多个异常),此时就会构造一个multiplefailureexception,这种设计可能是出于对防止测试方法中的exception被@after注解方法中的exception覆盖的问题引入的。
frameworkmethod是对java反射中method的封装,它提供了对方法的验证、调用以及处理子类方法隐藏父类方法问题,其主要提供的接口如下:
1 public method getmethod();
2 public object invokeexplosively(final object target, final object
params);
3 public string getname();
4 public void validatepublicvoidnoarg(boolean isstatic, list<throwable> errors);
5 public void validatepublicvoid(boolean isstatic, list<throwable> errors)
6 public void validatenotypeparametersonargs(list<throwable> errors);
7 @override
8 public boolean isshadowedby(frameworkmethod other);
9 @override
10 public annotation[] getannotations();
11 public <t extends annotation> t getannotation(class<t> annotationtype);
其中isshadowedby()方法用于处理子类方法隐藏父类方法的问题,junit支持测试类存在继承关系,并且会遍历所有父类的测试方法,但是如果子类的方法隐藏了父类的方法,则父类的方法不会被执行。这里的隐藏是指当子类的方法名、所有参数类型相同时,不管是静态方法还是非静态方法,都会被隐藏。其实现如下:
1 public boolean isshadowedby(frameworkmethod other) {
2 if (!other.getname().equals(getname()))
3 return false;
4 if (other.getparametertypes().length != getparametertypes().length)
5 return false;
6 for (int i= 0; i < other.getparametertypes().length; i++)
7 if (!other.getparametertypes()[i].equals(getparametertypes()[i]))
9 return false;
10 return true;
11 }
类似frameworkmethod,frameworkfield是对java反射中的field的封装,它提供了对字段取值、处理隐藏父类字段的问题,其主要提供的接口如下:
1 public string getname();
2 @override
3 public annotation[] getannotations();
4 public boolean ispublic();
5 @override
6 public boolean isshadowedby(frameworkfield othermember) {
7 return othermember.getname().equals(getname());
9 public boolean isstatic();
10 public field getfield();
11 public class<?> gettype();
12 public object get(object target)
13 throws illegalargumentexception, illegalaccessexception;
在处理隐藏问题是,它只是判断如果父类中某个字段的名和子类中某个字段的名字相同,则父类中的字段不会被junit处理,即被隐藏。事实上,关于隐藏的问题,只是对junit识别的方法和字段有效,即有junit相关注解的方法字段,其他方法并不受影响(事实上也是不可能受到影响)。
testclass是对java中class类的封装,在testclass构造过程中,它会收集所有传入class实例中具有注释的字段和方法,它会搜索类的所有继承结构。因而testclass的成员如下:
1 private final class<?> fclass;
2 private map<class<?>, list<frameworkmethod>> fmethodsforannotations;
3 private map<class<?>, list<frameworkfield>> ffieldsforannotations;
并且这些成员在testclass构造完后即已经初始化完成。在所有注解的收集过程中,它对@before和@beforeclass有一个特殊的处理,即父类中@before和@beforeclass的注解方法总是在之类之前,从而保证父类的@before和@beforeclass的注解方法会在子类的这些注解方法之前执行。而对@after和@afterclass的注解方法没有做处理,因而保持了之类的@after和@afterclass注解方法会在父类的这些注解方法之前执行。这段特殊逻辑是通过以下代码实现的(在addtoannotationlists()方法中,其中runstoptobottom()方法形象的表达了这个意思):
1 if (runstoptobottom(type))
2 members.add(0, member);
3 else
4 members.add(member);
在获得测试类中所有注解的方法和字段的map后,testclass提供了对annotation对应的方法和字段的查询接口:
1 public list<frameworkmethod> getannotatedmethods(
2 class<? extends annotation> annotationclass);
3 public list<frameworkfield> getannotatedfields(
4 class<? extends annotation> annotationclass);
5 public <t> list<t> getannotatedfieldvalues(object test,
6 class<? extends annotation> annotationclass,
7 class<t> valueclass);
以及测试类相关的信息,如class实例、名字、测试类中具有的annotation等:
1 public class<?> getjavaclass();
2 public string getname();
3 public constructor<?> getonlyconstructor();
4 public annotation[] getannotations();
5 public boolean isanonstaticinnerclass();
runner是junit中对所有runner的抽象,它只包括三个方法:
1 public abstract class runner implements describable {
3 public abstract void run(runnotifier notifier);
4 public int testcount() {
5 return getdescription().testcount();
6 }
7 }
其中getdescription()的实现已经在description相关的小节中做过计算了,不在重复,testcount()方法很简单,也已经实现了,因而本节主要介绍run()方法的运行过程,而该方法的实现则是在parentrunner中。
用parentrunner命名这个runner是想表达这是一个在测试方法树中具有子节点的节点,它的子节点可以是测试方法(blockjunit4classrunner)或者runner(suite)。parentrunner以测试类class实例作为构造函数的参数,在构造函数内部用testclass对测试类进行封装,并对一些那些规定的方法做验证:
1. @beforeclass和@afterclass注解的方法必须是public,void,static,无参
1 validatepublicvoidnoargmethods(beforeclass.class, true, errors);
2 validatepublicvoidnoargmethods(afterclass.class, true, errors);
2. 对有@classrule修饰的字段,必须是public,static,并且该字段的实例必须是实现了testrule接口的。为了兼容性,也可以实现methodrule接口。
在验证过程中,parentrunner通过一个list<throwable>收集所有的验证错误信息,如果存在错误信息,则验证不通过,parentrunner将抛出一个initializationerror的exception,该exception中包含了所有的错误信息,一般在这种情况下,会创建一个errorreportingrunner返回以处理验证出错的问题,该runner将在下面的小节中详细介绍。
在runner构造完成后,就可以调用run()方法运行该runner了:
2 public void run(final runnotifier notifier) {
3 eachtestnotifier testnotifier= new eachtestnotifier(notifier, getdescription());
5 try {
6 statement statement= classblock(notifier);
7 statement.evaluate();
8 } catch (assumptionviolatedexception e) {
9 testnotifier.firetestignored();
10 } catch (stoppedbyuserexception e) {
11 throw e;
12 } catch (throwable e) {
13 testnotifier.addfailure(e);
14 }
该方法的核心是构造一个statement实例,然后调用该实例的evaluate()方法。在junit中,statement是一个类链表,一个runner的执行过程就是这个statement类链表的执行过程。parentrunner对statement类链表的构造主要是对测试类级别的构造,如@beforeclass、@afterclass、@classrule等执行statement:
1 protected statement classblock(final runnotifier notifier) {
2 statement statement= childreninvoker(notifier);
3 statement= withbeforeclasses(statement);
4 statement= withafterclasses(statement);
5 statement= withclassrules(statement);
6 return statement;
7 }
8 protected statement childreninvoker(final runnotifier notifier) {
9 return new statement() {
10 @override
11 public void evaluate() {
12 runchildren(notifier);
14 };
16 private void runchildren(final runnotifier notifier) {
17 for (final t each : getfilteredchildren())
18 fscheduler.schedule(new runnable() {
19 public void run() {
20 parentrunner.this.runchild(each, notifier);
21 }
22 });
23 fscheduler.finished();
24 }
25 private list<t> getfilteredchildren() {
26 if (ffilteredchildren == null)
27 ffilteredchildren = new arraylist<t>(getchildren());
28 return ffilteredchildren;
29 }
30 protected abstract list<t> getchildren();
31 protected abstract void runchild(t child, runnotifier notifier);
其中getchildren()、runchild()方法由子类实现。
1 protected statement withbeforeclasses(statement statement) {
2 list<frameworkmethod> befores= ftestclass
3 .getannotatedmethods(beforeclass.class);
4 return befores.isempty() ? statement :
5 new runbefores(statement, befores, null);
6 }
7 protected statement withafterclasses(statement statement) {
8 list<frameworkmethod> afters= ftestclass
9 .getannotatedmethods(afterclass.class);
10 return afters.isempty() ? statement :
11 new runafters(statement, afters, null);
12 }
13 private statement withclassrules(statement statement) {
14 list<testrule> classrules= classrules();
15 return classrules.isempty() ? statement :
16 new runrules(statement, classrules, getdescription());
17 }
18 protected list<testrule> classrules() {
19 return ftestclass.getannotatedfieldvalues(null,
20 classrule.class, testrule.class);
关于statement将在下一节中详细讲,不过这里从statement的构造过程可以看出rule的执行要先于@beforeclass注解方法或晚于@afterclass注解方法。
在parentrunner关于执行方法的实现中,还有一个对每个测试方法statement链的执行框架的实现,其主要功能是加入事件发布和对异常的处理逻辑,从这里的statement实例是一个测试方法的运行整体,它包括了@before注解方法、@after注解方法以及@rule注解字段的testrule实例的运行过程,因而teststarted事件的发布是在@before方法运行之前,而testfinished事件的发布是在@after方法运行之后:
1 protected final void runleaf(statement statement, description description, runnotifier notifier) {
3 eachtestnotifier eachnotifier= new eachtestnotifier(notifier, description);
5 eachnotifier.fireteststarted();
6 try {
9 eachnotifier.addfailedassumption(e);
10 } catch (throwable e) {
11 eachnotifier.addfailure(e);
12 } finally {
13 eachnotifier.firetestfinished();
parentrunner还实现filterable接口和sortable接口,不过这里很奇怪的实现时为什么sorter要保存成字段,感觉这个完全可以通过方法参数实现,而filteredchildren字段的实现方式在多线程环境中运行的话貌似也会出问题。filter类主要提供一个shouldrun()接口以判断传入的description是否可以运行,若否,则将该description从parentrunner中移除;否则,将该filter应用到该child中,以处理child可能是filterable实例(parentrunner)的问题,从而以递归、先根遍历的方式遍历测试实例树上的所有节点,若一个父节点的所有子节点都被过滤了,则抛出notestremainexception:
1 public void filter(filter filter) throws notestsremainexception {
2 for (iterator<t> iter = getfilteredchildren().iterator();
3 iter.hasnext(); ) {
4 t each = iter.next();
5 if (shouldrun(filter, each))
6 try {
7 filter.apply(each);
8 } catch (notestsremainexception e) {
9 iter.remove();
10 }
11 else
12 iter.remove();
14 if (getfilteredchildren().isempty()) {
15 throw new notestsremainexception();
18 private boolean shouldrun(filter filter, t each) {
19 return filter.shouldrun(describechild(each));
junit中提供几种默认实现的filter:1. all不做任何过滤;2. matchmethoddescription只保留某个指定的测试方法。
1 public static filter all= new filter() {
2 @override
3 public boolean shouldrun(description description) {
4 return true;
5 }
6 @override
7 public string describe() {
8 return "all tests";
10 @override
11 public void apply(object child) throws notestsremainexception {
12 // 因为不会做任何过滤行为,因而不需要应用到子节点中
14 @override
15 public filter intersect(filter second) {
16 return second; // 因为本身没有任何过滤行为,所以可以直接返回传入的filter
18 };
19 public static filter matchmethoddescription(final description desireddescription) {
21 return new filter() {
22 @override
23 public boolean shouldrun(description description) {
24 if (description.istest())
25 return desireddescription.equals(description);
26 // explicitly check if any children want to run
27 for (description each : description.getchildren())
28 if (shouldrun(each))
29 return true;
30 return false;
31 }
32 @override
33 public string describe() {
34 return string.format("method %s", desireddescription.getdisplayname());
36 }
37 };
38 }
sorter类实现comparator接口,parentrunner通过其compare()方法构造和parentrunner子节点相关的comparator实例,并采用后根递归遍历的方式对测试方法树中的所有测试方法进行排序,因而这里只会排序同一个节点下的所有子节点,而节点之间的顺序不会受影响。
1 public void sort(sorter sorter) {
2 fsorter= sorter;
3 for (t each : getfilteredchildren())
4 sortchild(each);
5 collections.sort(getfilteredchildren(), comparator());
7 private comparator<? super t> comparator() {
8 return new comparator<t>() {
9 public int compare(t o1, t o2) {
10 return fsorter.compare(describechild(o1), describechild(o2));
12 }
13 };
14 }
最后parentrunner还提供了一个runnerscheduler的接口字段,以控制junit测试方法的执行过程,我们可以注入一个使用多线程方式运行每个测试方法的runnerscheduler,不过从代码上看,貌似junit对多线程的支持并不好,所以这个接口的扩展目前来看我还找不到什么用途:
1 public interface runnerscheduler {
2 void schedule(runnable childstatement);
3 void finished();
4 }
blockjunit4classrunner节点下所有的子节点都是测试方法,它是junit中运行测试方法的核心runner,它实现了parentrunner中没有实现的几个方法:
1 @override
2 protected list<frameworkmethod> getchildren() {
3 return computetestmethods();
4 }
5 protected list<frameworkmethod> computetestmethods() {
6 return gettestclass().getannotatedmethods(test.class);
7 }
8 @override
9 protected void runchild(final frameworkmethod method, runnotifier notifier) {
11 description description= describechild(method);
12 if (method.getannotation(ignore.class) != null) {
13 notifier.firetestignored(description);
14 } else {
15 runleaf(methodblock(method), description, notifier);
16 }
17 }
18 protected statement methodblock(frameworkmethod method) {
19 object test;
20 try {
21 test= new reflectivecallable() {
22 @override
23 protected object runreflectivecall() throws throwable {
24 return createtest();
25 }
26 }.run();
27 } catch (throwable e) {
28 return new fail(e);
29 }
30 statement statement= methodinvoker(method, test);
31 statement= possiblyexpectingexceptions(method, test, statement);
32 statement= withpotentialtimeout(method, test, statement);
33 statement= withbefores(method, test, statement);
34 statement= withafters(method, test, statement);
35 statement= withrules(method, test, statement);
36 return statement;
37 } //这个方法的实现可以看出每个测试方法运行时都会重新创建一个新的测试类实例,这也可能是@beforeclass、afterclass、@classrule需要静态的原因吧,因为静态的话,每次类实例的重新创建对其结果都不会有影响。
38 另,从这里对statement的构建顺序,junit对testrule的运行也要在@before注解方法之前或@after注解方法之后
39 protected object createtest() throws exception {
40 return gettestclass().getonlyconstructor().newinstance();
41 }
42 protected statement methodinvoker(frameworkmethod method, object test) {
43 return new invokemethod(method, test);
44 }
45 protected statement possiblyexpectingexceptions(frameworkmethod method, object test, statement next) {
47 test annotation= method.getannotation(test.class);
48 return expectsexception(annotation) ? new expectexception(next,
49 getexpectedexception(annotation)) : next;
50 }
51 private class<? extends throwable> getexpectedexception(test annotation) {
52 if (annotation == null || annotation.expected() == none.class)
53 return null;
54 else
55 return annotation.expected();
56 }
57 private boolean expectsexception(test annotation) {
58 return getexpectedexception(annotation) != null;
59 }
60 protected statement withpotentialtimeout(frameworkmethod method,
61 object test, statement next) {
62 long timeout= gettimeout(method.getannotation(test.class));
63 return timeout > 0 ? new failontimeout(next, timeout) : next;
64 }
65 private long gettimeout(test annotation) {
66 if (annotation == null)
67 return 0;
68 return annotation.timeout();
69 }
70 protected statement withbefores(frameworkmethod method, object target,
71 statement statement) {
72 list<frameworkmethod> befores= gettestclass().getannotatedmethods(
73 before.class);
74 return befores.isempty() ? statement : new runbefores(statement,
75 befores, target);
76 }
77 protected statement withafters(frameworkmethod method, object target,
78 statement statement) {
79 list<frameworkmethod> afters= gettestclass().getannotatedmethods(
80 after.class);
81 return afters.isempty() ? statement : new runafters(statement,
82 afters, target);
83 }
84 private statement withrules(frameworkmethod method, object target,
85 statement statement) {
86 statement result= statement;
87 result= withmethodrules(method, target, result);
88 result= withtestrules(method, target, result);
89 return result;
90 }
91 private statement withmethodrules(frameworkmethod method, object target,
92 statement result) {
93 list<testrule> testrules= gettestrules(target);
94 for (org.junit.rules.methodrule each : getmethodrules(target))
95 if (! testrules.contains(each))
96 result= each.apply(result, method, target);
97 return result;
98 }
99 private list<org.junit.rules.methodrule> getmethodrules(object target) {
100 return rules(target);
101 }
102 protected list<org.junit.rules.methodrule> rules(object target) {
103 return gettestclass().getannotatedfieldvalues(target, rule.class,
104 org.junit.rules.methodrule.class);
105 }
106 private statement withtestrules(frameworkmethod method, object target,
107 statement statement) {
108 list<testrule> testrules= gettestrules(target);
109 return testrules.isempty() ? statement :
110 new runrules(statement, testrules, describechild(method));
111 }
112 protected list<testrule> gettestrules(object target) {
113 return gettestclass().getannotatedfieldvalues(target,
114 rule.class, testrule.class);
115 }
在验证方面,blockjunit4classrunner也加入了一些和自己相关的验证:
1 @override
2 protected void collectinitializationerrors(list<throwable> errors) {
3 super.collectinitializationerrors(errors);
4 validatenononstaticinnerclass(errors);
5 validateconstructor(errors);
6 validateinstancemethods(errors);
7 validatefields(errors);
8 }
1. 如果测试类是一个类的内部类,那么该测试类必须是静态的:
1 protected void validatenononstaticinnerclass(list<throwable> errors) {
2 if (gettestclass().isanonstaticinnerclass()) {
3 string gripe= "the inner class " + gettestclass().getname()
4 + " is not static.";
5 errors.add(new exception(gripe));
2. 测试类的构造函数必须有且仅有一个无参的构造函数(事实上关于只有一个构造函数的验证在构造testclass实例的时候已经做了,因而这里真正起作用的知识对无参的验证):
1 protected void validateconstructor(list<throwable> errors) {
2 validateonlyoneconstructor(errors);
3 validatezeroargconstructor(errors);
4 }
5 protected void validateonlyoneconstructor(list<throwable> errors) {
6 if (!hasoneconstructor()) {
7 string gripe= "test class should have exactly one public constructor";
8 errors.add(new exception(gripe));
10 }
11 protected void validatezeroargconstructor(list<throwable> errors) {
12 if (!gettestclass().isanonstaticinnerclass()
13 && hasoneconstructor()
14 && (gettestclass().getonlyconstructor().getparametertypes().length != 0)) {
16 string gripe= "test class should have exactly one public zero-argument constructor";
17 errors.add(new exception(gripe));
18 }
19 }
20 private boolean hasoneconstructor() {
21 return gettestclass().getjavaclass().getconstructors().length == 1;
22 }
3. @before、@after、@test注解的方法必须是public,void,非静态,不带参数:
1 protected void validateinstancemethods(list<throwable> errors) {
2 validatepublicvoidnoargmethods(after.class, false, errors);
3 validatepublicvoidnoargmethods(before.class, false, errors);
4 validatetestmethods(errors);
5 if (computetestmethods().size() == 0)
6 errors.add(new exception("no runnable methods"));
8 protected void validatetestmethods(list<throwable> errors) {
9 validatepublicvoidnoargmethods(test.class, false, errors);
4. 带有@rule注解的字段必须是public,非静态,实现了testrule接口或methodrule接口。
1 private void validatefields(list<throwable> errors) {
2 rule_validator.validate(gettestclass(), errors);
写了好几天,终于把junit核心的执行所有代码分析完了,不过发现写的那么细,很多东西其实很难表达,因而贴了很多代码,感觉写的挺乱的,所以画一张序列图吧,感觉很多时候还是图的表达效果更好一些,要我看那么一大段的问题,也感觉挺烦的。
suite是其子节点是runner的runner,其内部保存了一个runner的list。suite的功能实现很简单,因为它将大部分的方法代理给了其内部runner实例:
1 private final list<runner> frunners;
3 protected list<runner> getchildren() {
4 return frunners;
5 }
6 @override
7 protected description describechild(runner child) {
8 return child.getdescription();
9 }
11 protected void runchild(runner runner, final runnotifier notifier) {
12 runner.run(notifier);
13 }
suite重点在于如何构建一个suite,suite提供两个构造函数:
1. 提供一个带suiteclasses注解的类,所有测试类由suiteclasses指定,而klass类作为这个suite的根类。此时一般所有的测试类是klass的内部类,因而可以通过@runwith指定运行klass类的runner是suite,然后用suiteclasses注解指定可以作为测试类的类。
1 public suite(class<?> klass, runnerbuilder builder) throws initializationerror {
3 this(builder, klass, getannotatedclasses(klass));
5 protected suite(runnerbuilder builder, class<?> klass, class<?>[] suiteclasses) throws initializationerror {
7 this(klass, builder.runners(klass, suiteclasses));
9 @retention(retentionpolicy.runtime)
10 @target(elementtype.type)
11 @inherited
12 public @interface suiteclasses {
13 public class<?>[] value();
15 private static class<?>[] getannotatedclasses(class<?> klass) throws initializationerror {
17 suiteclasses annotation= klass.getannotation(suiteclasses.class);
18 if (annotation == null)
19 throw new initializationerror(string.format("class '%s' must have a suiteclasses annotation", klass.getname()));
22 return annotation.value();
23 }
2. 在有些情况下,我们需要运行多个没有相关的测试类,此时这些测试类没有一个公共的根类的suite,则需要使用一下的构造函数(此时suite的getname()返回”null”,即其description的displayname的值为”null”,关于runnerbuilder将会在后面的文章中介绍):
1 public suite(runnerbuilder builder, class<?>[] classes) throws initializationerror {
3 this(null, builder.runners(null, classes));
5 protected suite(class<?> klass, list<runner> runners) throws initializationerror {
7 super(klass);
8 frunners = runners;
parameterized继承自suite,它类似blockjunit4classrunner是对一个测试类的运行过程的封装,但是它支持在测试类中定义一个获得参数数组的一个列表,从而可以为构造该测试类提供不同的参数值以进行多次测试。因而parameterized这个runner其实就是根据参数数组列表的个数创建多个基于该测试类的runner,并运行所有这些runner中测试方法。
由于这个测试类的构造函数是带参的,而blockjunit4classrunner则限制其测试类必须是不带参的,因而parameterized需要创建自己的runner,它集成自blockjunit4classrunner,除了构造函数的差别,parameterized的根节点是该测试类本身,它处理@beforeclass、@afterclass、@classrule的注解问题,因而其子节点的runner不需要重新对其做处理了,因而在集成的runner中应该避免这些方法、字段重复执行。
1 private class testclassrunnerforparameters extends blockjunit4classrunner {
3 private final int fparametersetnumber;
4 private final list<object[]> fparameterlist;
5 testclassrunnerforparameters(class<?> type, list<object[]> parameterlist, int i) throws initializationerror {
8 super(type);
9 fparameterlist= parameterlist;
10 fparametersetnumber= i; //参数数组列表中的位置
12 @override
13 public object createtest() throws exception {
14 return gettestclass().getonlyconstructor().newinstance(
15 computeparams());//带参创建测试类实例
17 private object[] computeparams() throws exception {
18 try {
19 return fparameterlist.get(fparametersetnumber);
20 } catch (classcastexception e) {
21 throw new exception(string.format(
22 "%s.%s() must return a collection of arrays.",
23 gettestclass().getname(), getparametersmethod(
24 gettestclass()).getname()));
25 }
27 @override
28 protected string getname() {
29 return string.format("[%s]", fparametersetnumber);
30 }
31 @override
32 protected string testname(final frameworkmethod method) {
33 return string.format("%s[%s]", method.getname(),
34 fparametersetnumber);
35 }
36 @override
37 protected void validateconstructor(list<throwable> errors) {
38 validateonlyoneconstructor(errors);//去除不带参构造函数验证
39 }
40 @override
41 protected statement classblock(runnotifier notifier) {
42 return childreninvoker(notifier);//不处理@beforeclass、
43 //@afterclass、@classrule等注解
44 }
45 @override
46 protected annotation[] getrunnerannotations() {
47 return new annotation[0];//去除测试类的annotation,这些应该在parameterized中处理
49 }
50 }
parameterized对suite的行为改变只是在创建runner集合的过程,parameterized通过类中查找@parameters注解的静态方法获得参数数组列表,并更具这个参数数组列表创建testclassrunnerforparameters的集合:
1 @retention(retentionpolicy.runtime)
2 @target(elementtype.method)
3 public static @interface parameters {
5 public parameterized(class<?> klass) throws throwable {
6 super(klass, collections.<runner>emptylist());
7 list<object[]> parameterslist= getparameterslist(gettestclass());
8 for (int i= 0; i < parameterslist.size(); i++)
9 runners.add(new testclassrunnerforparameters(gettestclass().getjavaclass(), parameterslist, i));
12 private list<object[]> getparameterslist(testclass klass)
13 throws throwable {
14 return (list<object[]>) getparametersmethod(klass).invokeexplosively(null);
16 }
17 private frameworkmethod getparametersmethod(testclass testclass)
18 throws exception {
19 list<frameworkmethod> methods= testclass.getannotatedmethods(parameters.class);
21 for (frameworkmethod each : methods) {
22 int modifiers= each.getmethod().getmodifiers();
23 if (modifier.isstatic(modifiers) &&
24 modifier.ispublic(modifiers))
25 return each;
27 throw new exception("no public static parameters method on class " + testclass.getname());
一个简单的parameterized测试类如下,不过如果在eclipse中单独的运行testequal()测试方法会出错,因为eclipse在filter传入的方法名为testequal,而在parameterized中这个方法名已经被改写成testequal[i]了,因而在filter过程中,所有的测试方法都被过滤掉了,此时会抛notestremainexception,而在eclipse中出现的则是initializationerror的exception,这里也是eclipse中junit的插件没有做好,它并没有给出failure类的详细信息:
1 public class parameterizedtest {
2 @parameters
3 public static list<object[]> data() {
4 return arrays.aslist(new object[][] {
5 { 0, 0 }, { 1, 1 }, { 2, 1 }, { 3, 2 },
6 { 4, 3 }, { 5, 5 }, { 6, 8 }
7 });
8 }
9 @beforeclass
10 public static void beforeclass() {
11 system.out.println("
.testing
.");
12 }
13 private final int input;
14 private final int expected;
15 public parameterizedtest(int input, int expected) {
16 this.input = input;
17 this.expected = expected;
18 }
19 @test
20 public void testequal() {
21 assert.assertequals(expected, compute(input));
22 }
23 public int compute(int input) {
24 if(input == 0 || input == 1) {
25 return input;
26 }
27 if(input == 2) {
28 return 1;
29 }
30 return compute(input -1) + compute(input - 2);
31 }
32 }
关于junit4,还剩下最后两个runner,分别是errorreportingrunner和ignoredclassrunner,为了编程模型的统一(这是一个非常好的设计想法,将各种变化都封装在runner中),junit中即使一个runner实例创建失败或是该测试类有@ignored的注解,在这两种情况中,junit分别通过errorreportingrunner和ignoredclassrunner去表达。在errorreportingrunner中,为每个exception发布测试失败的信息;ignoredclassrunner则只是发布testignored事件:
1 public class errorreportingrunner extends runner {
2 private final list<throwable> fcauses;
3 private final class<?> ftestclass;
4 public errorreportingrunner(class<?> testclass, throwable cause) {
5 ftestclass= testclass;
6 fcauses= getcauses(cause);
9 public description getdescription() {
10 description description= description.createsuitedescription(ftestclass);
12 for (throwable each : fcauses)
13 description.addchild(describecause(each));
14 return description;
17 public void run(runnotifier notifier) {
18 for (throwable each : fcauses)
19 runcause(each, notifier);
21 @suppresswarnings("deprecation")
22 private list<throwable> getcauses(throwable cause) {
23 if (cause instanceof invocationtargetexception)
24 return getcauses(cause.getcause());
25 if (cause instanceof initializationerror)
26 return ((initializationerror) cause).getcauses();
27 if (cause instanceof org.junit.internal.runners.initializationerror)
28 return ((org.junit.internal.runners.initializationerror) cause)
29 .getcauses();
30 return arrays.aslist(cause);
32 private description describecause(throwable child) {
33 return description.createtestdescription(ftestclass,
34 "initializationerror");
36 private void runcause(throwable child, runnotifier notifier) {
37 description description= describecause(child);
38 notifier.fireteststarted(description);
39 notifier.firetestfailure(new failure(description, child));
40 notifier.firetestfinished(description);
41 }
42 }
43 public class ignoredclassrunner extends runner {
44 private final class<?> ftestclass;
45 public ignoredclassrunner(class<?> testclass) {
46 ftestclass= testclass;
48 @override
49 public void run(runnotifier notifier) {
50 notifier.firetestignored(getdescription());
52 @override
53 public description getdescription() {
54 return description.createsuitedescription(ftestclass);
55 }
56 }
写了一个周末了,这一篇终于是写完了,初次尝试将阅读框架源码以文字的形式表达出来,确实不好写,感觉自己写的太详细了,也贴了太多源码,因为有些时候感觉源码比文字更有表达能力,不过太多的源码就把很多实质的东西掩盖了,然后文章看起来也没有什么大的价值干,而且太长了,看到那么多的东西,要我自己看到也就有不想看的感觉,1万多字啊,呵呵。总之以后慢慢改进吧,这一篇就当是练习了,不想复工了,也没那么多的时间重写。。。。。。