JUnit
JUnit is a testing tool for Java. It helps you write down, structure, and
run your test cases. JUnit is not a magical tool that tries to come up with test
cases for you automatically!
See JUnit's home-page, in
particular the Getting
Started page.
Install and Use
Installing JUnit is very easy.
- Get JUnit by either:
- downloading the distribution
from www.junit.org
- in case you run Linux, check whether your distribution offers
JUnit (Ubunt does), and install it
In either case, make sure you use JUnit4 or higher.
No further installation is needed!
- When writing a test class, import the following:
import org.junit.*;
import static org.junit.Assert.*;
To mark a method (for instance
testMethodName)
as a test case
annotate it with @Test, e.g.:
@Test public void testMethodName() { ... }
To decide whether a test was successful, the test method makes the
following call:
assertTrue(condition);
where condition is a condition for the test being successful.
- For compiling and running your tests, the java classpath must
include the .jar file of JUnit (like junit-4.x.jar,
or junit4.jar, or alike). You can achieve that through
setting the classpath environment variable, or by giving the
classpath as an option (-cp) to javac and java.
- under Windows:
- compile test:
javac -cp .;pathToAndIncludingJunitJarFile YourTestClass.java
- To run all methods annotated with @Test in a class:
java -cp .;pathToAndIncludingJunitJarFile
org.junit.runner.JUnitCore YourTestClass
- under Linux:
- compile test:
javac -cp .:pathToAndIncludingJunitJarFile YourTestClass.java
- To run all methods annotated with @Test in a class:
java -cp .:pathToAndIncludingJunitJarFile
org.junit.runner.JUnitCore YourTestClass
where pathToAndIncludingJunitJarFile
and YourTestClass are named accordingly.
You can read more about using JUnit in the
JUnit Cookbook.
|