junit4源码浅析

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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值