原文出处:http://www.blogjava.net/DLevin/archive/2012/05/12/377955.html。感谢作者的无私分享。

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

深入JUnit源码之Rule

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注解字段的验证

@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     

 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) {

        optionallyValidateStatic(field, errors);

        validatePublic(field, errors);

        validateTestRuleOrMethodRule(field, errors);

     }

     private void optionallyValidateStatic(FrameworkField field,

            List<Throwable> errors) {

        if (fOnlyStaticFields && !field.isStatic())

            addError(errors, field, "must be static.");

     }

     private void validatePublic(FrameworkField field, List<Throwable> errors) {

        if (!field.isPublic())

            addError(errors, field, "must be public.");

     }

     private void validateTestRuleOrMethodRule(FrameworkField field,

            List<Throwable> errors) {

        if (!isMethodRule(field) && !isTestRule(field))

            addError(errors, field, "must implement MethodRule or TestRule.");

     }

     private boolean isTestRule(FrameworkField target) {

        return TestRule.class.isAssignableFrom(target.getType());

     }

     private boolean isMethodRule(FrameworkField target) {

        return org.junit.rules.MethodRule.class.isAssignableFrom(target

               .getType());

     }

     private void addError(List<Throwable> errors, FrameworkField field,

            String suffix) {

        String message= "The @" + fAnnotation.getSimpleName() + " '"

               + field.getName() + "' " + suffix;

        errors.add(new Exception(message));

     }

 }

JUnit默认实现的TestRule

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

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

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

TestWatcher和TestName

先来看两个简单的吧,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);

               } catch (AssumptionViolatedException e) {

                   throw e;

               } catch (Throwable t) {

                   failed(t, description);

                   throw t;

               } finally {

                   finished(description);

               }

            }

        };

     }

     protected void succeeded(Description description) {

     }

     protected void failed(Throwable e, Description description) {

     }

     protected void starting(Description description) {

     }

     protected void finished(Description description) {

     }

 }

 public class TestName extends TestWatcher {

     private String fName;

     @Override

     protected void starting(Description d) {

        fName= d.getMethodName();

     }

     public String getMethodName() {

        return fName;

     }

 }

ExternalResource与TemporaryFolder

ExternalResource为子类提供了两个接口,分别是进入测试之前和退出测试之后,一般它是作为对一些资源在测试前后的控制,如Socket的开启与关闭、Connection的开始与断开、临时文件的创建与删除等。如果ExternalResource用在@ClassRule注解字段中,before()方法会在所有@BeforeClass注解方法之前调用;after()方法会在所有@AfterClass注解方法之后调用,不管在执行@AfterClass注解方法时是否抛出异常。如果ExternalResource用在@Rule注解字段中,before()方法会在所有@Before注解方法之前调用;after()方法会在所有@After注解方法之后调用。

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();

               try {

                   base.evaluate();

               } finally {

                   after();

               }

            }

        };

     }

     protected void before() throws Throwable {

     }

     protected void after() {

     }

 }

 public class TemporaryFolder extends ExternalResource {

     private File folder;

     @Override

     protected void before() throws Throwable {

        create();

     }

     @Override

     protected void after() {

        delete();

     }

     public void create() throws IOException {

        folder= newFolder();

     }

     public File newFile(String fileName) throws IOException {

        File file= new File(getRoot(), fileName);

        file.createNewFile();

        return file;

     }

     public File newFile() throws IOException {

        return File.createTempFile("junit", null, folder);

     }

     public File newFolder(String folderNames) {

        File file = getRoot();

        for (String folderName : folderNames) {

            file = new File(file, folderName);

            file.mkdir();

        }

        return file;

     }

     public File newFolder() throws IOException {

        File createdFolder= File.createTempFile("junit", "", folder);

        createdFolder.delete();

        createdFolder.mkdir();

        return createdFolder;

     }

     public File getRoot() {

        if (folder == null) {

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

        }

        return folder;

     }

     public void delete() {

        recursiveDelete(folder);

     }

     private void recursiveDelete(File file) {

        File[] files= file.listFiles();

        if (files != null)

            for (File each : files)

               recursiveDelete(each);

        file.delete();

     }

 }

Verifier和ErrorCollector

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) {

 3        return new Statement() {

 4            @Override

 5            public void evaluate() throws Throwable {

 6               base.evaluate();

 7               verify();

 8            }

 9        };

     }

     protected void verify() throws Throwable {

     }

 }

 public class ErrorCollector extends Verifier {

     private List<Throwable> errors= new ArrayList<Throwable>();

     @Override

     protected void verify() throws Throwable {

        MultipleFailureException.assertEmpty(errors);

     }

     public void addError(Throwable error) {

        errors.add(error);

     }

     public <T> void checkThat(final T value, final Matcher<T> matcher) {

        checkThat("", value, matcher);

     }

     public <T> void checkThat(final String reason, final T value, final Matcher<T> matcher) {

        checkSucceeds(new Callable<Object>() {

            public Object call() throws Exception {

               assertThat(reason, value, matcher);

               return value;

            }

        });

     }

     public Object checkSucceeds(Callable<Object> callable) {

        try {

            return callable.call();

        } catch (Throwable e) {

            addError(e);

            return null;

        }

     }

 }

Timeout与ExpectedException

Timeout与ExpectedException都是对@Test注解中timeout和expected字段的部分替代实现。而且不同于@Test中的注解只适用于单个测试方法,这两个实现适用于全局测试类。对Timeout来说,如果不是在测试类中所有的测试方法都需要有时间限制,我并不推荐适用Timeout;对ExpectedException,它使用了hamcrest中的Matcher来匹配,因而提供了更强大的控制能力,但是一般的使用,感觉@Test中的expected字段就够了,它多次调用expected表达是and的关系,即如果我有两个Exception,则抛出的Exception必须同时是这两个类型的,感觉没有什么大的意义,因而我不怎么推荐使用这个Rule,关于hamcrest的Mather框架将在Assert小节中详细介绍。这两个Rule原本就是基于测试方法设计的,因而如果应用在@ClassRule上好像没有什么大的意义,不过Timeout感觉是可以应用在@ClassRule中的,如果要测试一个测试类整体运行时间的话,当然如果存在这种需求的话。

 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);

 8     }

 9 }

 public class ExpectedException implements TestRule {

     public static ExpectedException none() {

        return new ExpectedException();

     }

     private Matcher<Object> fMatcher= null;

     private ExpectedException() {

     }

     public Statement apply(Statement base,

            org.junit.runner.Description description) {

        return new ExpectedExceptionStatement(base);

     }

     public void expect(Matcher<?> matcher) {

        if (fMatcher == null)

            fMatcher= (Matcher<Object>) matcher;

        else

            fMatcher= both(fMatcher).and(matcher);

     }

     public void expect(Class<? extends Throwable> type) {

        expect(instanceOf(type));

     }

     public void expectMessage(String substring) {

        expectMessage(containsString(substring));

     }

     public void expectMessage(Matcher<String> matcher) {

        expect(hasMessage(matcher));

     }

     private class ExpectedExceptionStatement extends Statement {

        private final Statement fNext;

        public ExpectedExceptionStatement(Statement base) {

            fNext= base;

        }

        @Override

        public void evaluate() throws Throwable {

            try {

               fNext.evaluate();

            } catch (Throwable e) {

               if (fMatcher == null)

                   throw e;

               Assert.assertThat(e, fMatcher);

               return;

            }

            if (fMatcher != null)

               throw new AssertionError("Expected test to throw "

                      + StringDescription.toString(fMatcher));

        }

     }

     private Matcher<Throwable> hasMessage(final Matcher<String> matcher) {

        return new TypeSafeMatcher<Throwable>() {

            public void describeTo(Description description) {

               description.appendText("exception with message ");

               description.appendDescriptionOf(matcher);

            }

            @Override

            public boolean matchesSafely(Throwable item) {

               return matcher.matches(item.getMessage());

            }

        };

     }

 }

RuleChain

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

 @Rule

 public TestRule chain= RuleChain

                     .outerRule(new LoggingRule("outer rule"))

                     .around(new LoggingRule("middle rule"))

                     .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);

     }

     private RuleChain(List<TestRule> rules) {

        this.rulesStartingWithInnerMost= rules;

     }

     public RuleChain around(TestRule enclosedRule) {

        List<TestRule> rulesOfNewChain= new ArrayList<TestRule>();

        rulesOfNewChain.add(enclosedRule);

        rulesOfNewChain.addAll(rulesStartingWithInnerMost);

        return new RuleChain(rulesOfNewChain);

     }

     public Statement apply(Statement base, Description description) {

        for (TestRule each : rulesStartingWithInnerMost)

            base= each.apply(base, description);

        return base;

     }

 }

TestRule在Statement的运行

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);

 5     }

 6     @Override

 7     public void evaluate() throws Throwable {

 8        statement.evaluate();

 9     }

     private static Statement applyAll(Statement result, Iterable<TestRule> rules,

            Description description) {

        for (TestRule each : rules)

            result= each.apply(result, description);

        return result;

     }

 }

junit4X系列--Rule的更多相关文章

  1. junit4X系列--Runner解析

    前面我整理了junit38系列的源码,那junit4X核心代码也基本类似.这里我先转载一些关于junit4X源码解析的好文章.感谢原作者的分享.原文地址:http://www.blogjava.net ...

  2. Junit4X系列--hamcrest的使用

    OK,在前面的一系列博客里面,我整理过了Assert类下面常用的断言方法,比如assertEquals等等,但是org.junit.Assert类下还有一个方法也用来断言,而且更加强大.这就是我们这里 ...

  3. junit4X系列源码--Junit4 Runner以及test case执行顺序和源代码理解

    原文出处:http://www.cnblogs.com/caoyuanzhanlang/p/3534846.html.感谢作者的无私分享. 前一篇文章我们总体介绍了Junit4的用法以及一些简单的测试 ...

  4. junit4X系列源码--总体介绍

    原文出处:http://www.cnblogs.com/caoyuanzhanlang/p/3530267.html.感谢作者的无私分享. Junit是一个可编写重复测试的简单框架,是基于Xunit架 ...

  5. junit4X系列--Exception

    原文出处:http://www.blogjava.net/DLevin/archive/2012/11/02/390684.html.感谢作者的无私分享. 说来惭愧,虽然之前已经看过JUnit的源码了 ...

  6. junit4X系列--Builder、Request与JUnitCore

    原文出处:http://www.blogjava.net/DLevin/archive/2012/05/12/377957.html.感谢作者的无私分享. 初次用文字的方式记录读源码的过程,不知道怎么 ...

  7. junit4X系列--Statement

    原文出处:http://www.blogjava.net/DLevin/archive/2012/05/11/377954.html.感谢作者的无私分享. 初次用文字的方式记录读源码的过程,不知道怎么 ...

  8. junit4X系列--Assert与Hamcrest

    原文出处:http://www.blogjava.net/DLevin/archive/2012/05/12/377960.html.感谢作者无私分享 到目前,JUnit4所有的核心源码都已经讲解过了 ...

  9. junit测试延伸--方法的重复测试

    在实际编码测试中,我们有的时候需要对一个方法进行多次测试,那么怎么办呢?这个问题和测试套件解决的方案一样,我们总不能不停的去右键run as,那怎么办呢?还好伟大的junit帮我们想到了. OK,现在 ...

随机推荐

  1. python3之模块

    1.python3模块 模块是一个包含所有你定义的函数和变量的文件,其后缀名是.py.模块可以被别的程序引入,以使用该模块中的函数等功能.这也是使用 python 标准库的方法. 模块让你能够有逻辑地 ...

  2. 汇编debug与masm命令

    汇编语言这块是我之前写在网易博客上的,不过那个账号基本已经作废了,所以现在抽个时间把当时的博客搬到CSDN上. 汇编命令(编译器masm命令):找到masm所在的文件夹,我的在d:\MASM中,用cm ...

  3. python中将字典形式的数据循环插入Excel

    1.我们看到字典形式的数据如下所示 list=[["2891-1", "D"],["2892-1", "D"],[&qu ...

  4. C#学习笔记-装饰模式

    题目:给顾客打扮,但是需要满足正常的穿衣风格,例如先穿了衬衣再打领带,最后在穿鞋子,这种基本要求. 分析: 现在将具体的衣服裤子和鞋子都分别写在不同的类里面,这样方便以后添加新的衣服,这些全部都属于服 ...

  5. 【Spring】DispatcherServlet源码分析

    使用过HttpServlet的都应该用过其doGet和doPost方法,接下来看看DispatcherServlet对这两个方法的实现(源码在DispatcherServlet的父类Framework ...

  6. 大搜车知乎live中的面试题结题方法记录

    1.HTML&CSS(分别10分) 1. 一个div,宽度是100px,此时设置padding是20px,添加一个什么css属性可以让div的实际宽度仍然保持在100px,而不是140px? ...

  7. 数据结构之链表-链表实现及常用操作(C++篇)

    数据结构之链表-链表实现及常用操作(C++篇) 0.摘要 定义 插入节点(单向链表) 删除节点(单向链表) 反向遍历链表 找出中间节点 找出倒数第k个节点 翻转链表 判断两个链表是否相交,并返回相交点 ...

  8. sqlmap完成简单的sql注入

    扫描目标站点,是否存在注入 --users获取用户名 --dump --tables探测表和数据库信息 跑出来的字段 admin --dump -T admin -C admin,password暴库 ...

  9. Gym 100952E&&2015 HIAST Collegiate Programming Contest E. Arrange Teams【DFS+剪枝】

    E. Arrange Teams time limit per test:2 seconds memory limit per test:64 megabytes input:standard inp ...

  10. BZOJ 1257: [CQOI2007]余数之和sum【神奇的做法,思维题】

    1257: [CQOI2007]余数之和sum Time Limit: 5 Sec  Memory Limit: 162 MBSubmit: 4474  Solved: 2083[Submit][St ...