Junit 源码剖析(二)
junit4 下的所有的testcase都是在Runner下执行的, 可以将Runner理解为junit运行的容器, 默认情况下junit会使用JUnit4ClassRunner作为所有testcase的执行容器。
如果要定制自己的junit, 则可以实现自己的Runner,最简单的办法就是Junit4ClassRunner继承, spring-test, unitils这些框架就是采用这样的做法。
如在spring中是SpringJUnit4ClassRunner, 在unitils中是UnitilsJUnit4TestClassRunner, 一般我们的testcase都是在通过eclipse插件来执行的, eclipse的junit插件会在执行的时候会初始化指定的Runner。初始化的过程可以在ClassRequest中找到。
org.junit.internal.runners.Junit4ClassRunner
package org.junit.internal.runners; import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List; import org.junit.runner.Description;
import org.junit.runner.Runner;
import org.junit.runner.manipulation.Filter;
import org.junit.runner.manipulation.Filterable;
import org.junit.runner.manipulation.NoTestsRemainException;
import org.junit.runner.manipulation.Sortable;
import org.junit.runner.manipulation.Sorter;
import org.junit.runner.notification.Failure;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner; /**
* @deprecated Included for backwards compatibility with JUnit 4.4. Will be
* removed in the next release. Please use
* {@link BlockJUnit4ClassRunner} in place of
* {@link JUnit4ClassRunner}.
*
* This may disappear as soon as 1 April 2009
*/
@Deprecated
public class JUnit4ClassRunner extends Runner implements Filterable, Sortable
{
private final List<Method> fTestMethods; private TestClass fTestClass; //将要测试的TestCase实例Class对象传入
public JUnit4ClassRunner(Class<?> klass) throws InitializationError
{
fTestClass = new TestClass(klass);
fTestMethods = getTestMethods();
//对要进行测试的方法展开验证
validate();
} //获取@test的方法List
protected List<Method> getTestMethods()
{
return fTestClass.getTestMethods();
} //对要进行测试的方法展开验证
protected void validate() throws InitializationError
{
MethodValidator methodValidator = new MethodValidator(fTestClass);
methodValidator.validateMethodsForDefaultRunner();
methodValidator.assertValid();
} @Override
public void run(final RunNotifier notifier)
{
new ClassRoadie(notifier, fTestClass, getDescription(), new Runnable()
{
public void run()
{
runMethods(notifier);
}
}).runProtected();
} protected void runMethods(final RunNotifier notifier)
{
for (Method method : fTestMethods)
invokeTestMethod(method, notifier);
} @Override
public Description getDescription()
{
Description spec = Description.createSuiteDescription(getName(), classAnnotations());
List<Method> testMethods = fTestMethods;
for (Method method : testMethods)
spec.addChild(methodDescription(method));
return spec;
} protected Annotation[] classAnnotations()
{
return fTestClass.getJavaClass().getAnnotations();
} protected String getName()
{
return getTestClass().getName();
} protected Object createTest() throws Exception
{
return getTestClass().getConstructor().newInstance();
} protected void invokeTestMethod(Method method, RunNotifier notifier)
{
Description description = methodDescription(method);
Object test;
try
{
test = createTest();
}
catch(InvocationTargetException e)
{
testAborted(notifier, description, e.getCause());
return;
}
catch(Exception e)
{
testAborted(notifier, description, e);
return;
}
TestMethod testMethod = wrapMethod(method);
new MethodRoadie(test, testMethod, notifier, description).run();
} private void testAborted(RunNotifier notifier, Description description, Throwable e)
{
notifier.fireTestStarted(description);
notifier.fireTestFailure(new Failure(description, e));
notifier.fireTestFinished(description);
} protected TestMethod wrapMethod(Method method)
{
return new TestMethod(method, fTestClass);
} protected String testName(Method method)
{
return method.getName();
} protected Description methodDescription(Method method)
{
return Description.createTestDescription(getTestClass().getJavaClass(), testName(method), testAnnotations(method));
} protected Annotation[] testAnnotations(Method method)
{
return method.getAnnotations();
} public void filter(Filter filter) throws NoTestsRemainException
{
for (Iterator<Method> iter = fTestMethods.iterator(); iter.hasNext();)
{
Method method = iter.next();
if (!filter.shouldRun(methodDescription(method)))
iter.remove();
}
if (fTestMethods.isEmpty())
throw new NoTestsRemainException();
} public void sort(final Sorter sorter)
{
Collections.sort(fTestMethods, new Comparator<Method>()
{
public int compare(Method o1, Method o2)
{
return sorter.compare(methodDescription(o1), methodDescription(o2));
}
});
} protected TestClass getTestClass()
{
return fTestClass;
}
}
org.junit.internal.runners.TestClass类
不同于上一节提到的org.junit.runners.model.TestClass类
package org.junit.internal.runners; import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runners.BlockJUnit4ClassRunner; /**
* @deprecated Included for backwards compatibility with JUnit 4.4. Will be
* removed in the next release. Please use
* {@link BlockJUnit4ClassRunner} in place of
* {@link JUnit4ClassRunner}.
*/
@Deprecated
public class TestClass
{
private final Class<?> fClass; public TestClass(Class<?> klass)
{
fClass = klass;
} public List<Method> getTestMethods()
{
return getAnnotatedMethods(Test.class);
} List<Method> getBefores()
{
return getAnnotatedMethods(BeforeClass.class);
} List<Method> getAfters()
{
return getAnnotatedMethods(AfterClass.class);
} public List<Method> getAnnotatedMethods(Class<? extends Annotation> annotationClass)
{
List<Method> results = new ArrayList<Method>();
for (Class<?> eachClass : getSuperClasses(fClass))
{
Method[] methods = eachClass.getDeclaredMethods();
for (Method eachMethod : methods)
{
Annotation annotation = eachMethod.getAnnotation(annotationClass);
if (annotation != null && !isShadowed(eachMethod, results))
results.add(eachMethod);
}
}
if (runsTopToBottom(annotationClass))
Collections.reverse(results);
return results;
} private boolean runsTopToBottom(Class<? extends Annotation> annotation)
{
return annotation.equals(Before.class) || annotation.equals(BeforeClass.class);
} private boolean isShadowed(Method method, List<Method> results)
{
for (Method each : results)
{
if (isShadowed(method, each))
return true;
}
return false;
} private boolean isShadowed(Method current, Method previous)
{
if (!previous.getName().equals(current.getName()))
return false;
if (previous.getParameterTypes().length != current.getParameterTypes().length)
return false;
for (int i = 0; i < previous.getParameterTypes().length; i++)
{
if (!previous.getParameterTypes()[i].equals(current.getParameterTypes()[i]))
return false;
}
return true;
} private List<Class<?>> getSuperClasses(Class<?> testClass)
{
ArrayList<Class<?>> results = new ArrayList<Class<?>>();
Class<?> current = testClass;
while (current != null)
{
results.add(current);
current = current.getSuperclass();
}
return results;
} public Constructor<?> getConstructor() throws SecurityException, NoSuchMethodException
{
return fClass.getConstructor();
} public Class<?> getJavaClass()
{
return fClass;
} public String getName()
{
return fClass.getName();
} }
org.junit.internal.runners.MethodValidator类
用于在org.junit.internal.runners.Junit4ClassRunner 类当中进行方法验证
package org.junit.internal.runners; import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runners.BlockJUnit4ClassRunner; /**
* @deprecated Included for backwards compatibility with JUnit 4.4. Will be
* removed in the next release. Please use
* {@link BlockJUnit4ClassRunner} in place of {@link JUnit4ClassRunner}.
*/
@Deprecated
public class MethodValidator { private final List<Throwable> fErrors= new ArrayList<Throwable>(); private TestClass fTestClass; //org.junit.internal.runners.JUnit4ClassRunner类中
//validate()方法中调用该构造函数-----第一步
public MethodValidator(TestClass testClass) {
fTestClass = testClass;
} public void validateInstanceMethods() {
validateTestMethods(After.class, false);
validateTestMethods(Before.class, false);
validateTestMethods(Test.class, false); List<Method> methods= fTestClass.getAnnotatedMethods(Test.class);
if (methods.size() == 0)
fErrors.add(new Exception("No runnable methods"));
} public void validateStaticMethods() {
validateTestMethods(BeforeClass.class, true);
validateTestMethods(AfterClass.class, true);
} //Junit4ClassRunner类中调用第二步
public List<Throwable> validateMethodsForDefaultRunner() {
//校验无参构造方法
validateNoArgConstructor();
//校验注解方法
validateStaticMethods();
validateInstanceMethods();
return fErrors;
} //Junit4ClassRunner类中第三步
public void assertValid() throws InitializationError {
if (!fErrors.isEmpty())
throw new InitializationError(fErrors);
} public void validateNoArgConstructor() {
try {
fTestClass.getConstructor();
} catch (Exception e) {
fErrors.add(new Exception("Test class should have public zero-argument constructor", e));
}
} //校验要测试的方法 是否静态方法、是否public方法、是否返回值void、是否无参数
//@param annotation 要测试的annotation类
//@param isStatic 是否要求静态方法
private void validateTestMethods(Class<? extends Annotation> annotation,boolean isStatic) {
List<Method> methods= fTestClass.getAnnotatedMethods(annotation); for (Method each : methods) {
if (Modifier.isStatic(each.getModifiers()) != isStatic) {
String state= isStatic ? "should" : "should not";
fErrors.add(new Exception("Method " + each.getName() + "() "
+ state + " be static"));
}
if (!Modifier.isPublic(each.getDeclaringClass().getModifiers()))
fErrors.add(new Exception("Class " + each.getDeclaringClass().getName()
+ " should be public"));
if (!Modifier.isPublic(each.getModifiers()))
fErrors.add(new Exception("Method " + each.getName()
+ " should be public"));
if (each.getReturnType() != Void.TYPE)
fErrors.add(new Exception("Method " + each.getName()
+ " should be void"));
if (each.getParameterTypes().length != 0)
fErrors.add(new Exception("Method " + each.getName()
+ " should have no parameters"));
}
}
}
Junit 源码剖析(二)的更多相关文章
- Django Rest Framework源码剖析(二)-----权限
一.简介 在上一篇博客中已经介绍了django rest framework 对于认证的源码流程,以及实现过程,当用户经过认证之后下一步就是涉及到权限的问题.比如订单的业务只能VIP才能查看,所以这时 ...
- Qt信号槽源码剖析(二)
大家好,我是IT文艺男,来自一线大厂的一线程序员 上节视频给大家讲解了Qt信号槽的基本概念.元对象编译器.示例代码以及Qt宏:今天接着深入分析,进入Qt信号槽源码剖析系列的第二节视频. Qt信号槽的宏 ...
- jdk源码剖析二: 对象内存布局、synchronized终极原理
很多人一提到锁,自然第一个想到了synchronized,但一直不懂源码实现,现特地追踪到C++层来剥开synchronized的面纱. 网上的很多描述大都不全,让人看了不够爽,看完本章,你将彻底了解 ...
- Junit 源码剖析(一)
采用Junit4.8.2分析Junit实现架构 源码架构两个大包:junit包 org包 首先分析org.junit.runners.model包下的几个类 org.junit.runners.mod ...
- Dubbo源码剖析二之注册中心
Dubbo基础二之架构及处理流程概述 - 池塘里洗澡的鸭子 - 博客园 (cnblogs.com)中架构中,无论是服务提供者还是服务消费者都离不开注册中心,可见注册中心之重要.Redis.Nacos. ...
- muduo库源码剖析(二) 服务端
一. TcpServer类: 管理所有的TCP客户连接,TcpServer供用户直接使用,生命期由用户直接控制.用户只需设置好相应的回调函数(如消息处理messageCallback)然后TcpSer ...
- boost.asio源码剖析(二) ---- 架构浅析
* 架构浅析 先来看一下asio的0层的组件图. (图1.0) io_object是I/O对象的集合,其中包含大家所熟悉的socket.deadline_tim ...
- jdk源码剖析:Synchronized
开启正文之前,先说一下源码剖析这一系列,就以"死磕到底"的精神贯彻始终,最少追踪到JVM指令(再往下C语言实现了). =========正文分割线=========== Sync ...
- jdk源码剖析一:OpenJDK-Hotspot源码包目录结构
开启正文之前,先说一下源码剖析这一系列,就以“死磕到底”的精神贯彻始终,JDK-->JRE-->JVM(以openJDK代替) 最近想看看JDK8源码,但JDK中JVM(安装在本地C:\P ...
随机推荐
- C#通过FTP账号上传、修改、删除文件 FTPClient
下面类文件中,主要做的工作是:从ftp服务器上下载文件把本地文件替换.添加.或删除功能,在替换本地文件时会先备份一下本地的文件,若整个操作都完成了就会发出commit命令,表示全部替换成功.若中间操作 ...
- PowerMock注解PowerMockIgnore的使用方法
故事要从一个异常开始,某天我在开发一个加密.解密特性,算法使用的是3DES,样例代码如下. package org.jackie.study.powermock; import java.io.Uns ...
- Swipecards
https://github.com/Diolor/Swipecards https://github.com/kikoso/Swipeable-Cards
- careercup-链表 2.2
2.2 实现一个算法,找到单链表中倒数第k个节点. 这道题的考点在于我们怎么在一个单链表中找到倒数第n个元素? 由于是单链表,所以我们没办法从最后一个元素数起,然后数n个得到答案. 但这种最直观的思路 ...
- 基于heartbeat的单播方式实现tomcat高可用
1.节点规划 在master.backup节点上添加eth0.eth1两网卡,具体添加过程,参考“基于VMware为CentOS 6.5配置两个网卡” 2.IP规划 master backup e ...
- iOS网络层架构设计分享
前言 前些天帮公司做了网络层的重构,当时就想做好了就分享给大家,后来接着做了新版本的需求,现在才有时间整理一下. 之前的网络层使用的是直接拖拽导入项目的方式导入了AF,然后还修改了大量的源码,时隔2年 ...
- Java基础知识强化之集合框架笔记53:Map集合之Map集合的遍历 键值对对象找键和值
1. Map集合的遍历(键值对对象找键和值) Map -- 夫妻对 思路: A: 获取所有结婚证的集合 B: 遍历结婚证的集合,得到每一个结婚证 C: 根据结婚证获取丈夫和妻子 转换: A: ...
- Linux文件查找命令find用法整理(locate/find)
Linux文件查找查找主要包括:locate和find 1.locate 用法简单,根据数据库查找,非实时,用法: locate FILENAME 手动更新数据库(时间可能较长) updatedb 2 ...
- Linux系统ifconfig命令找不到,centos ifconfig Command not found
centos ifconfig Command not found,Linux系统ifconfig命令找不到 >>>>>>>>>>>& ...
- android开发:点击缩略图查看大图
android中点击缩略图查看大图的方法一般有两种,一种是想新浪微博list页面那样,弹出一个窗口显示大图(原activity为背景).另一种就是直接打开一个新的activity显示大图. 1.第一种 ...