JUnit is a testing framework aimed at making unit testing easy by
simplifying the writing of test cases and by providing automated
running
of tests and test suites. Most programmers use only informal test
methods.We think about the various cases to test for and we perform
them
manually by interacting with the unit/module. The problem with this
approach
is that it is very tedious to do and is also very repetitive. Students
generally don’t like to test because of the boring and tedious
repetition. By
automating the process, testing becomes less painful, more reliable,
and
less time consuming. Furthermore, by using a framework, the process of
writing
the test case is as easy as following a recipe.
Download the JUnit Jar file: junit.jar
(version 3.8)
Make your classpath variable point to junit.jar.
For
example, if the jar file is located in a directory named C:\junit3.8:
(Windows) set classpath=%classpath%;C:\junit3.8\junit.jar;.
(Alternately, you can provide the -classpath argument when
you invoke the java command.)
Let's write unit tests for the Rationals
class from the Lewis and
Loftus text. You can read the typical, cumbersome approach to testing
in
his RationalNumbers class
on page 196.
JUnit provides a TestRunner tool to perform the actual run of the
test. The TestRunner classes take a Test class and runs all its
methods. It provides
feedback via the asserts. TestRunner will report how many tests were
successful,
how many failed, and how long the tests took. The asserts will tell you
where the error occurred and implicitly what the error was.
If all the tests pass, you get a pretty green bar, otherwise you
get a red bar.
To run the TestRunner:
java junit.swingui.TestRunner <your test class>You can either specify the test class at the commandline or load it from within the GUI. The [your test class] parameter becomes optional.
for example: java junit.swingui.TestRunner RationalTest
There is also a text version of the TestRunner,
junit.textui.TestRunner, which is preferable
for use in batch testing. For example:
java -cp .:/usr/local/bluej/lib/junit.jar
junit.textui.TestRunner <your test class>
References
JUnit
Primer
JUnit How-To
Test Infected:
Programmers Love Writing Tests
Another helpful reference is the Assert
class javadocs.
* This will give your test case access to
"package
private" members.