`

junit4源码浅析

    博客分类:
  • Test
阅读更多
junit3和junit4是两个非常不同的版本, 不能简单的理解为是后者是前者的一个升级, 二者的内部实现有很大的不同。 这里只针对junit4以后的版本。
所有的testcase都是在Runner下执行的, 可以将Runner理解为junit运行的容器, 默认情况下junit会使用JUnit4ClassRunner作为所有testcase的执行容器。 如果要定制自己的junit, 则可以实现自己的Runner,最简单的办法就是Junit4ClassRunner继承, spring-test, unitils这些框架就是采用这样的做法。如在spring中是SpringJUnit4ClassRunner, 在unitils中是UnitilsJUnit4TestClassRunner, 一般我们的testcase都是在通过eclipse插件来执行的, eclipse的junit插件会在执行的时候会初始化指定的Runner。初始化的过程可以在ClassRequest中找到:
	@Override
	public Runner getRunner() {
		return buildRunner(getRunnerClass(fTestClass)); 
	}

	public Runner buildRunner(Class<? extends Runner> runnerClass) {
		try {
			return runnerClass.getConstructor(Class.class).newInstance(new Object[] { fTestClass });
		} catch (NoSuchMethodException e) {
			String simpleName= runnerClass.getSimpleName();
			InitializationError error= new InitializationError(String.format(
					CONSTRUCTOR_ERROR_FORMAT, simpleName, simpleName));
			return Request.errorReport(fTestClass, error).getRunner();
		} catch (Exception e) {
			return Request.errorReport(fTestClass, e).getRunner();
		}
	}

	Class<? extends Runner> getRunnerClass(final Class<?> testClass) {
		if (testClass.getAnnotation(Ignore.class) != null)
			return new IgnoredClassRunner(testClass).getClass();
		RunWith annotation= testClass.getAnnotation(RunWith.class);
		if (annotation != null) {
			return annotation.value();
		} else if (hasSuiteMethod() && fCanUseSuiteMethod) {
			return AllTests.class;
		} else if (isPre4Test(testClass)) {
			return JUnit38ClassRunner.class; 
		} else {
			return JUnit4ClassRunner.class;
		}
	}

这里的局部变量fTestClass是当前的testcase类, 如果使用了注解, 它会从RunWith中拿到指定的Runner, 所以要定制的话, 最方便的做法就是通过@RunWith指定定制的Runner, Spring-test, Unitils都是这么干的^_^
下面来看JUnit4ClassRunner的构造器:
public JUnit4ClassRunner(Class<?> klass) throws InitializationError {
		fTestClass= new TestClass(klass);
		fTestMethods= getTestMethods();
		validate();
	}

JUnit4ClassRunner没有默认的构造器, 从构造器中我们可以看出, 它需要一个参数, 这个参数就是我们当前要运行的testcase class, Runner拿到了要执行的testcase类之后, 就可以进一步拿到需要执行的测试方法, 这个是通过注解拿到的:
	
	protected List<Method> getTestMethods() {
		return fTestClass.getTestMethods();
	}

	List<Method> getTestMethods() {
		return getAnnotatedMethods(Test.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;
	}

初始化完成之后, 就可以根据拿到的Runner, 调用其run方法,执行所有的测试方法了:
	@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);
	}

	protected void invokeTestMethod(Method method, RunNotifier notifier) {
		Description description= methodDescription(method);
		Object test;
		try {
			test= createTest();
		} catch (InvocationTargetException e) {
			notifier.testAborted(description, e.getCause());
			return;			
		} catch (Exception e) {
			notifier.testAborted(description, e);
			return;
		}
		TestMethod testMethod= wrapMethod(method);
		new MethodRoadie(test, testMethod, notifier, description).run();
	}

这里很多地方都利用了线程技术, 可以忽略不管, 最终都是要通过反射拿到需要执行的测试方法并调用, 最终的调用在MethodRoadie中:
	public void run() {
		if (fTestMethod.isIgnored()) {
			fNotifier.fireTestIgnored(fDescription);
			return;
		}
		fNotifier.fireTestStarted(fDescription);
		try {
			long timeout= fTestMethod.getTimeout();
			if (timeout > 0)
				runWithTimeout(timeout);
			else
				runTest();
		} finally {
			fNotifier.fireTestFinished(fDescription);
		}
	}
	
	public void runTest() {
		runBeforesThenTestThenAfters(new Runnable() {
			public void run() {
				runTestMethod();
			}
		});
	}

	public void runBeforesThenTestThenAfters(Runnable test) {
		try {
			runBefores();
			test.run();
		} catch (FailedBefore e) {
		} catch (Exception e) {
			throw new RuntimeException("test should never throw an exception to this level");
		} finally {
			runAfters();
		}		
	}
	
	protected void runTestMethod() {
		try {
			fTestMethod.invoke(fTest);
			if (fTestMethod.expectsException())
				addFailure(new AssertionError("Expected exception: " + fTestMethod.getExpectedException().getName()));
		} catch (InvocationTargetException e) {
			Throwable actual= e.getTargetException();
			if (actual instanceof AssumptionViolatedException)
				return;
			else if (!fTestMethod.expectsException())
				addFailure(actual);
			else if (fTestMethod.isUnexpected(actual)) {
				String message= "Unexpected exception, expected<" + fTestMethod.getExpectedException().getName() + "> but was<"
					+ actual.getClass().getName() + ">";
				addFailure(new Exception(message, actual));
			}
		} catch (Throwable e) {
			addFailure(e);
		}
	}

下面是使用spring-test的runner如何来写testcase, 将会有不少简化(推荐懒人使用):
要测试的方法:
public class ExampleObject {

	public boolean getSomethingTrue() {
		return true;
	}

	public boolean getSomethingFalse() {
		return false;
	}
}

测试用例:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext.xml" })
public class ExampleTest {
	@Autowired
	ExampleObject objectUnderTest;

	@Test
	public void testSomethingTrue() {
		Assert.assertNotNull(objectUnderTest);
		Assert.assertTrue(objectUnderTest.getSomethingTrue());
	}

	@Test
	@Ignore
	public void testSomethingElse() {
		Assert.assertNotNull(objectUnderTest);
		Assert.assertTrue(objectUnderTest.getSomethingFalse());
	}
}

xml配置:
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="objectUnderTest" class="com.taobao.demo.spring.test.ExampleObject">
    </bean>
</beans>

如果是使用maven的话, pom.xml的配置:
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>2.5.5</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>2.5.4</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>2.5.4</version>
		</dependency>
	</dependencies>

6
0
分享到:
评论
2 楼 skyuck 2011-03-25  
学习了,楼主整理的很好
1 楼 xly_971223 2009-04-23  
楼主整理的非常好
只是版本太老了

junit4.6已经废弃了JUnit4ClassRunner类

好多的方法名字都变了

相关推荐

    Junit4完整源码

    JUnit4源码的完整版本包含了整个框架的实现细节,对于理解其工作原理、学习测试驱动开发(TDD)以及进行自定义扩展非常有帮助。 1. **JUnit核心概念**: - **Test Case**:在JUnit4中,测试用例是通过继承`org....

    junit 的源码jar包

    junit 的源码jar包 junit 的源码jar包 junit 的源码jar包

    junit4 单元测试源码

    【标题】"junit4 单元测试源码"涉及的是Java编程中单元测试的重要工具JUnit4的使用,这是对代码进行验证和调试的关键部分。JUnit4是JUnit框架的一个版本,它提供了更灵活的注解、测试套件管理和断言方式,使得编写...

    JUnit4.8.1源码包

    JUnit4.8.1源码包 版本4.8.1 只有源码。

    junit4测试源码

    这个"junit4测试源码"可能包含了JUnit4框架的源代码,使得用户能够深入理解其内部工作原理,便于自定义扩展或学习测试驱动开发(TDD)的最佳实践。 首先,JUnit4引入了注解(Annotation)的概念,使得测试类和测试...

    Junit Recipes 源码

    《Junit Recipes 源码》是一份宝贵的资源,它包含了一系列与单元测试相关的实践案例,主要用于学习和应用JUnit测试框架。JUnit是Java编程语言中最常用的单元测试工具,它为开发者提供了一种简单且强大的方式来编写可...

    junit4 jar包以及源码

    JUnit4是Java编程语言中最广泛使用的单元测试框架之一,它为开发者提供了编写和运行可重复、可靠的测试用例的工具。这个压缩包包含了两个重要的文件:`junit-4.11.jar` 和 `junit-4.11-sources.jar`。 `junit-4.11....

    Junit4单元测试源码

    JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。 [1] JUnit是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework)。Junit测试是...

    junit4测试源码 免费

    这个"junit4测试源码 免费"的资源包含的是JUnit4框架的源代码,这对于理解其内部工作原理、学习如何编写更高效、更健壮的测试用例以及进行自定义扩展具有极大的价值。 JUnit4引入了许多新特性,极大地提高了测试的...

    junit4.12源码

    junit4.12源码,便于查看源码,重写方法,为己所用。

    junit in action 源码

    7. **测试规则**:JUnit4中的TestRule接口和JUnit5中的Extension API提供了扩展测试行为的能力,如日志记录、性能测试等。通过源码,我们可以学习如何自定义测试规则。 8. **异步测试**:随着并发编程的普及,JUnit...

    Junit4使用教程详解+源码下载.rar

    本教程将深入讲解JUnit4的使用方法,并附带源码供学习者实践和参考。 一、JUnit4概述 JUnit4是JUnit系列的第四个主要版本,它引入了许多新特性,如注解(Annotations)、参数化测试、测试套件的改进以及更加灵活的...

    junit4测试jar包

    JUnit4测试框架是Java开发中广泛使用的单元测试工具,它为开发者提供了编写和运行可重复、可靠的测试用例的能力。这个“junit4测试jar包”包含了一切你需要在项目中集成JUnit4进行测试的库文件。只需将其复制到你的...

    junit源码以及牵涉到的设计模式

    ### JUnit源码及其涉及的设计模式 #### 一、引言 JUnit作为一款广泛应用于Java项目的单元测试框架,其设计理念和实现方式对于软件开发者来说具有很高的学习价值。本文将深入探讨JUnit源码,并重点关注其中使用的...

    junit4 jar完整包

    JUnit4是Java编程语言中最广泛使用的单元测试框架之一,它为开发者提供了一种方便、高效的方式来验证代码的正确性。这个“junit4 jar完整包”包含了所有你需要进行单元测试的类和接口,使得测试过程变得简单且易于...

    junit4测试数据库源码

    本资料包"junit4测试数据库源码"主要涵盖了Junit4的新特性assertThat断言以及如何利用Junit4进行MySQL和Oracle两种主流数据库的增删改查操作的测试。 首先,我们来了解一下Junit4的assertThat断言。在旧版本的Junit...

    junit4 jar包

    JUnit4是Java编程语言中最广泛使用的单元测试框架之一,它为开发者提供了编写可重复执行、易于维护的测试代码的能力。这个“junit4 jar包”包含了运行JUnit4测试所必需的库文件,主要包括两个核心组件:`junit-4.11....

    Junit源码分析(圣思园)

    **Junit源码分析(圣思园)** Junit是Java编程语言中最广泛使用的单元测试框架,它使得开发者能够方便地编写和运行可重复的、可靠的测试用例。本篇文章将深入探讨Junit的源码,揭示其内部工作原理,帮助我们更好地...

    junit4学习文档

    ### JUnit4 学习知识点详解 #### 一、JUnit4 概述 JUnit4 是 JUnit 测试框架的一个重大更新版本,它充分利用了 Java 5 的注解(Annotation)特性来简化测试用例的编写过程。注解是一种元数据,用于描述程序中的...

    junit4教程(《Junit4初探》)

    **JUnit4教程——初探单元测试的艺术** JUnit4是Java编程语言中广泛使用的单元测试框架,它是Java开发者进行软件质量保证的重要工具。本教程将深入浅出地介绍JUnit4的基本概念、核心特性以及如何在实际项目中应用它...

Global site tag (gtag.js) - Google Analytics