7. JUnit testing
Testing is an important part of the programming progress. One kind of testing is unit testing, in which one unit, usually a method, is tested. Here, we describe how unit testing is done in Eclipse using JUnit testing, the J standing for Java.
Learn how to create and use a JUnit testing class
Read this page to see how to create a JUnit testing class in Java.
Checking that your testing worked
We illustrate the mechanics of testing, showing you (1) how to run a test, (2) what the results of a test look like, and (3) how to check what was actually tested. Point (3) is important! It is easy to make a small mistake and think that your testing worked while in reality nothing was tested. People get bitten by this all the time. After seeing this video, it shouldn't happen to you. (4 minutes) Read it here: JUnit mechanics.pdf
Writing assertEquals statements to test a static function
Read this page to see how to write a testing procedure to test a function that returns the minimum of three values. You'll learn about the use of procedure assertEquals, the main tool for testing whether a computed value is correct.
Testing that a constructor does its job
Read this page to see what it means for a constructor to do its job and how one writes test cases for it.
Testing that an instance does its job
Read this page to see how to test an instance method.
Read this pdf file to see what other methods are available besides assertEquals.
Read this pdf file to how to test whether an assert statement to test a precondition was written properly.
Read this pdf file to how to test whether a method call throws a particular exception.
A few guidelines for JUnit testing classes
1. Make the name of a testing procedure indicate what the procedure is for, e.g. testConstructor1 and testIsBefore. Then, no specification is needed, because (1) these methods are fairly straightforward and (2) everyone knows generally what they are for. This is one case where complete and thorough javadoc specifications are not needed.
2. Don't spread the testing of one method over several testing procedures. Instead, make each testing procedure focused and to the point. Example: have a testing procedure completely test one constructor, or completely test one or two instance functions.
3. Don't use fields or static variables in a Junit testing class. Make all variables local variables of testing procedures. You don't know the order in which testing procedures are called, and you don't have complete understanding of JUnit testing classes.
4. Once something has been tested using a testing procedure, leave that testing procedure alone; don't change it unless a change is required for a real reason. It's OK, and good, to test it again every time the testing class is run.