junit是java中書寫unit test的framework,目前一些流行的unit test工具大都都是在junit上擴(kuò)展而來的。本文針對(duì)的的版本是junit3.8.1,可以從www.junit.org上下載。新版本是junit4.1,一般新的myeclipse開發(fā)環(huán)境中都集成了的。
安裝
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的使用非常簡(jiǎn)單,它的基本使用步驟:
- 創(chuàng)建,從junit.framework.TestCase派生unit test需要的test case
- 書寫測(cè)試方法,提供類似于如下函數(shù)簽名的測(cè)試方法:
public void testXXXXX();
- 編譯,書寫完test case后,編譯所寫的test case類
- 運(yùn)行,啟動(dòng)junit test runner,來運(yùn)行這個(gè)test case。
Junit提供了2個(gè)基本的test runner:字符界面和圖形界面。啟動(dòng)命令分別如下:
a 圖形界面:
java junit.swingui.TestRunner XXXXX
b 字符界面:
java junit.textui.TestRunner XXXXX