Java Tutorial - Java Script :
Unit Testing: JUnit
Testing is one way to ensure software quality. Languages like Java make it easy to test code while it is being developed because the language supports encapsulation and code independence. Testing a single functional piece of code is known as unit testing. JUnit is a set of utilities designed to aid in unit testing Java classes. The philosophy behind JUnit is that as developers create methods for a class they can also create tests to ensure that each method works as designed. These tests can be executed as a collection in a test plan. The test plan is executed on classes each time a class is changed to ensure that the changes have not broken other elements of the code. If a bug or anomaly is found that was not caught by the test plan, then a new test can be added to the test plan to specifically test for that bug. Future changes will continue to execute all tests in the plan to ensure that a future fix does not break earlier ones. This execution of all previous tests is sometimes known as regression testing.
The following table provides a product summary for JUnit.
To gain a better understanding of unit testing with JUnit, let’s work through a simple example. Our sample code will be a class called Palindrome. Palindrome stores a single string object and returns that string either the way it was stored or reversed. The class definition follows:
/*== save as Palindrome.java */
/**
* Palindrome is a demonstration class for use
* in demonstrating the use of the jUnit testing framework.
* @author jtbell
*/
public class Palindrome extends java.lang.Object
{
private StringBuffer s = null;
/** Creates a new instance of Palindrome */
public Palindrome()
{
}
public Palindrome( String aString ) {
s = new StringBuffer( aString );
}
void setString(String aString)
{
s = new StringBuffer( aString );
}
String getString()
{
if( s != null)
return s.toString();
else
return null;
}
String getReverse()
{
if( s != null)
return s.reverse().toString();
else
return null;
}
}
There are two methods that we want to test in Palindrome: getString and getReverse. In the past, good programmers would test their code by creating main methods that exercised the class. JUnit goes beyond this type of testing by providing a testing framework that allows multiple complex tests to be defined and easily combined. To start creating a JUnit test, we need to derive a new class from the junit.framework.TestCase class as follows:
import junit.framework.*;
public class PalindromeTest extends TestCase
{
public PalindromeTest(java.lang.String testName)
{
super(testName);
}
}
