junit是java中书写unit test的framework,目前一些流行的unit test工具大都都是在junit上扩展而来的。本文针对的的版本是junit3.8.1,可以从www.junit.org上下载。新版本是junit4.1,一般新的myeclipse开发环境中都集成了的。
安装
First, download the latest version of JUnit, referred to below as junit.zip.
Then install JUnit on your platform. of choice:
Windows
To install JUnit on Windows, follow these steps:
Unzip the junit.zip distribution file to a directory referred to as %JUNIT_HOME%.
Add JUnit to the classpath:
set CLASSPATH=%CLASSPATH%;%JUNIT_HOME%junit.jar
Unix (bash)
To install JUnit on Unix, follow these steps:
Unzip the junit.zip distribution file to a directory referred to as $JUNIT_HOME.
Add JUnit to the classpath:
export CLASSPATH=$CLASSPATH:$JUNIT_HOME/junit.jar
(Optional) Unzip the $JUNIT_HOME/src.jar file.
Test the installation by using either the textual or graphical test runner to run the sample tests distributed with JUnit.
Note: The sample tests are not contained in the junit.jar, but in the installation directory directly. Therefore, make sure that the JUnit installation directory is in the CLASSPATH.
For the textual TestRunner, type:
java junit.textui.TestRunner junit.samples.AllTests
For the graphical TestRunner, type:
java junit.swingui.TestRunner junit.samples.AllTests
All the tests should pass with an "OK" (textual) or a green bar (graphical).
If the tests don't pass, verify that junit.jar is in the CLASSPATH.
Finally, read the documentation.
用法
1. 基本使用步骤,Junit的使用非常简单,它的基本使用步骤:
- 创建,从junit.framework.TestCase派生unit test需要的test case
- 书写测试方法,提供类似于如下函数签名的测试方法:
public void testXXXXX();
- 编译,书写完test case后,编译所写的test case类
- 运行,启动junit test runner,来运行这个test case。
Junit提供了2个基本的test runner:字符界面和图形界面。启动命令分别如下:
a 图形界面:
java junit.swingui.TestRunner XXXXX
b 字符界面:
java junit.textui.TestRunner XXXXX