由于yqj2065下载使用的BlueJ集成的是JUnit4.8.2,所以就分析一下JUnit4.8.2的源代码。
JUnit是由GOF 之一的Erich Gamma 和 Kent Beck 编写的一个开源的单元测试框架,分析JUnit源代码的主要目的是学习其中对设计模式的运用。JUnit也是一个研究如何应对版本升级和接口变化的案例。
阅读源代码,首先需要知道该框架的设计需求。如果使用过JUnit,单元测试的需求应该比较熟悉。从简单的例子入手,有应用程序(待测试的类)HelloWorld,为了使用JUnit4测试它,需要设计一个HelloWorldTest,当然,在BlueJ中我们不需要敲代码。
package myTest;
public class HelloWorld {
public double add(double m,double n){
return m+n;
}
public double add2(double m,double n){
return m+n;
}
}
package myTest;
import org.junit.Test;//@Test
import static org.junit.Assert.*;//assertEquals
public class TestInJUnit4{
@Test
public void add(){
HelloWorld h = new HelloWorld();
assertEquals(7.0, h.add(1, 2), 0.1);
}
}
单元测试类TestInJUnit4则是手工敲的代码,单元测试类图标为暗绿色,可以直接执行其@Test方法。
JUnit将处理的是单元测试类,@Test等标注/Annotation定义一项测试。JUnit通过反射解析RUNTIME标注,
单元测试类的一个测试用例/a test case是一个public void 方法。
package org.junit;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Test {
/**
* Default empty exception
*/
static class None extends Throwable {
private static final long serialVersionUID= 1L;
private None() {
}
}
/**
* Optionally specify <code>expected</code>, a Throwable, to cause a test method to succeed iff
* an exception of the specified class is thrown by the method.
*/
Class<? extends Throwable> expected() default None.class;
/**
* Optionally specify <code>timeout</code> in milliseconds to cause a test method to fail if it
* takes longer than that number of milliseconds.*/
long timeout() default 0L;
}
org.junit.Ignore @Target({ElementType.METHOD, ElementType.TYPE})
@Before和@After标示的方法只能各有一个,取代了JUnit以前版本中的setUp和tearDown方法
org.junit.BeforeClass @Target(ElementType.METHOD)
org.junit.Before @Target(ElementType.METHOD)
org.junit.AfterClass @Target(ElementType.METHOD)
org.junit.After @Target(ElementType.METHOD)
org.junit.runner.RunWith 使用指定Runner运行测试。默认的Runner为org.junit.runners.JUnit4。
org.junit.runners.Suite.SuiteClasses将所有需要运行的测试类组成组/ Suite,一次性的运行以方便测试工作。
org.junit.runners.Parameterized.Parameters参数化测试
原文:http://blog.csdn.net/yqj2065/article/details/39839155