Java Workshop

Unit Testing


Acting or operating in a manner essentially independent of external influence or control.
An object instance is created by calling the constructor of a class. A constructor is method-like block of code that is called when the object is created. Typically constructors initialize data members and acquire resources the abject may require.
A Skeletal software component that performs functions required by a system and which is incorporated into the design of such systems.
The capabilities or behaviors of a program, application, or system; the total set of its features.
To load and configure a piece of software on a computer.
Logical Unit
A group of code blocks or statements that together form a logical cohesive whole.
Test Case
A set of conditions or variables under which a tester will determine if a requirement upon an application is partially or fully satisfied. It may take many test cases to determine that a requirement is fully satisfied.
Test Driven Development
Test-driven development (TDD) is a programming technique heavily emphasized in Extreme Programming. Essentially the technique involves writing your tests first then implementing the code to make them pass.
Test Suite
A test suite is a set of related tests, usually pertaining to a group of features or software component.
Unit Test
A unit test is a method of testing the correctness of a particular module of source code.


Testing code is an important aspect of software development as it ensures that the code is correct, does what is intended and does not contain any errors or bugs.

Unit testing allows the developer to test every logical unit of code. This has one considerable benefit, code can easily be changed without fear since the unit tests will quickly determine if the code changes have broken the code. We will look at unit testing in this chapter using the JUnit framework.

When combined with a source version control system, this is a very powerfu combination, since if the changes break the code, the changes can be reverted, but if the changes are good they can be included in the code base. This process is known as refactoring.

You can get JUnit @

Test Driven Programming

In this section we will briefly look at where Unit Testing comes from, why it is important and how it fits into the big picture of software development. I hope you will find this section informative even though it is a brief overview.

Extreme Programming

eXtreme Programming commonly referred to as XP is a process for developing software that was created in order to provide for the trend in which many software development projects would overrun their schedule and budgets. Developing software is not an easy task and one requires a development methodology that takes numerous factors into account.

With XP, there is constant interaction with the client of the software, this means that the questions the developers have are answered quickly, the client also gets to see the progress of the project. Frequent small releases keep the client satisfied.

There are twelve principles that XP focuses on, but for many the core principles are:

Simplicity is what the development team should strive for. Find the simplest working solution to the problem.
Unit Testing
Using unit testing, the development team can determine if their solution is a working solution. It is no good to have a solution that doesn't solve the problem, testing is used to ensure the code does what is intended.
Refactoring is the process of making changes to the code and its design in an effort to improve or simplify it. If you have a solution but it isn't the simplest solution you need to refactor it.

What is Unit Testing?

It is common sense that all code developed by a software developer should be tested, this is generally understood. We can further this and say that every logical unit of code should be tested. And it would be good if these tests are automated and even better if they can be incorporated into the build process. This is unit testing, automated testing of each logical unit of code.

Each class in object-oriented programming is a logical unit of code, we therefore need to test each and every class's code. A class consists of variables and methods. All variables should be declared as private and used by the methods of the class, any public or unused variables should be refactored. All private and protected methods should be used by the public methods of the class, if not the unused methods should be refactored. Given this, by testing the class's public methods it should be clear that we in effect test all the class's code.

Needless to say, a unit test tests the public methods of a class to verify that it is correct and does what is intended.

The Test, Code, Design Cycle

Traditional software development practices focus on first designing the code, then writing the code and finally testing it. in XP, the opposite is true, we first write the test, then write the code and finally we consider its design and refactor if necessary.

Writing the test first may seem like a ridiculous idea especially for code that hasn't been written yet, but I urge you to give it a try. By writing the test first, you are carefully considering what needs to go into the code, what functionality of the code should be tested.

This is known as test driven development. Unit testing in this case actually drives the functionality of the code and you end up writing only sufficient code to run the tests and no more. This means you don't write any unused code and all the code you write has a test for it.

Once the test is written you can then write the code to make the test compile and run. The first time you run the tests you may get errors, this is not a bad thing as it shows you how the code is constantly changing to get the tests to run and succeed.

After the tests are run you should first attempt to fix any failures if there are any and finaly look at the code and consider if it needs to be refactored. While looking at the code ask yourself: Is it the simplest working solution? If not, you need to refactor it.

Writing Unit Tests

In this section we'll look at the code that goes into a unit test and what is involved in actually writing the tests. In the next section I'll show you how to run the tests. As an example consider writing a unit test for the java.util.Vector class. Although the code for Vector has already been written, instead of the test first approach, we can still use it as an example.

Test Cases

For every class we will write a test case. In our example we will only write one test case since we plan to only test the Vector class. It should come as no surprise that a test case is a class that inherits from (subclasses) junit.framework.TestCase.

Every test case has a single constructor that takes a string parameter and passes this to the constructor of the junit.framework.TestCase class using super constructing. Assume the test we're writing has a class name VectorTest, the constructor is as follows:

public VectorTest(String name) {

Every test case also has a suite method that is used by the test framework to set up the test suite and run the tests. In our test case this method is as follows:

public static Test suite() {
    return new TestSuite(VectorTest.class);

If you need to initialize resources or free resources in the test case you can override the setUp and tearDown methods of the junit.framework.TestCase class. In our test case we want to init alize a variable named vector and set it to null when we're finished with it, as follows:

protected void setUp() {
    vector = new Vector();		

protected void tearDown() {
    vector = null;

The Test Methods

Finally we get to the actual testing of the class. Every test method has a method signature: public void and the name must begin with test. The names should also be informative since they are used in the output when a test fails. Consider a method to test adding an object to the vector:

public void testAddObject() {
    Integer i = new Integer(7);
    assertTrue(vector.size() == 1);

Note the last line of this method body contains an assertTrue statement. This is used by the test framework to verify that the expression is indeed true. If it is not true, the assertion fails causing the test to fail. Consider another test, to remove an object from the vector and verify that this is the case:

public void testRemoveObject() {
    Integer j = new Integer(3);

We can continue to add test methods to test every public method of the Vector class. It is important to note that the setUp and tearDown methods are called for each individual test, so every test method starts with an empty vector. This implies that the Integer object i added in the testAddObject cannot be removed in the testRemoveObject method, which is why we add a new object before removing it.

Running JUnit With Ant

One of the aspects of unit testing is that the test should be automated and preferably part of the build process. To get this we will incorporate JUnit into Ant and have ant run the tests with our build.

Install JUnit in Ant

In order to run JUnit with ant you need to install JUnit in Ant. This is easily done. First extract the JUnit archive to a location of your choice. The resulting folder will be named junitversion and will contain a jar file named junit.jar.

Copy this jar file (junit.jar) to the lib directory in your ant directory. The ant directory is the directory you specified as ANT_HOME when you installed ant.

The Test Targets

How you structure your source code was discussed in the previous chapter, but we need to revise this structure a bit to incorporate unit tests into the code base. We want to keep our code base clean so the last thing we want to do is to mix the actual source code of the project with the unit test source code.

A good way to achieve this is to have a java and test directory within the src directory. The java directory will contain our java code and the test directory will contain our unit tests. I also like to keep all the tests in a package named test but some people prefer to use their inverted domain name as discussed in the chapter on java packages: com.mycompany.myproject.test

The structure can be seen in the image below.

Directory Structure

Compile Tests Target

Once you have the correct directory structure its time to add the required targets to the ant build file. The first thing we need to do is compile our tests before we can run them. Our tests also depend on the application's code being compiled so our target will depend on the compile target. It is important to add the application's compiled classes and the junit jar to the classpath:

<target name="compile.tests" depends="compile"
        description="o Compile unit test cases.">
    <mkdir dir="build"/>
    <javac srcdir="src/test"
            <pathelement location="build"/>
            <pathelement location="lib/junit.jar"/>

Run Tests Target

To run the tests we use the junit task with a nested batchtest task that runs all files with a "Test" in the filename. For more information on the tasks and their options see the Ant manual.

<target name="test" depends="compile.tests"
        description="o Run all unit test cases.">        
    <junit printsummary="no" haltonfailure="yes" showoutput="yes">
            <pathelement location="build"/>
            <pathelement location="lib/junit.jar"/>
        <formatter type="brief" />
        <batchtest fork="yes" todir="build">
            <fileset dir="src/test">
                <include name="**/*Test*.java"/>
            <formatter type="brief" usefile="false" />

Running The Tests

To run the test you simply type ant test in the command line from within the project root directory. This will compile the unit tests and run them.

In our example application, the output is:

Buildfile: F:\chapter7\build.xml
     [echo] Compiled.
    [junit] Testsuite: test.VectorTest
    [junit] Tests run: 2, Failures: 0, Errors: 0, Time elapsed: 0 sec
Total time: 1 second                

You can get the source code from this chapter here:


Unit Testing provides an excellent way in which to test all the code in your application. It is easily incorporated into the build process using Apache Ant and facilitates refactoring of the code. JUnit is the unit test framework for the java platform.

Exercise Set

Multiple Choice

  1. Testing code ensures

    1. The code is correct
    2. Does what is intended
    3. Does not contain any errors
    4. All the above
    5. None of the above
  2. Unit testing allows the developer to test every logical unit of code

    1. True
    2. False
  3. The development team should strive for:

    1. Simplicity
    2. Refactoring
    3. Unit Testing
  4. Unit Tests should be

    1. Automated
    2. Integrated into the build process
    3. Run by Ant
    4. All the above
    5. None of the above
  5. Testing a class's public methods is sufficient in testing the class.

    1. True
    2. False
  6. The process is

    1. Design - Code - Test
    2. Code - Test - Design
    3. Test - Code - Design
    4. Code - Design - Test
    5. Design - Code - Test
  7. A Test Case should subclass junit.framework.TestCase.

    1. True
    2. False
  8. The suite method returns

    1. junit.framework.Suite
    2. junit.framework.Test
    3. junit.framework.TestSuite
  9. Initialising resourecs is done in the ... method?

    1. constrcutor
    2. setUp
    3. tearDown
  10. assertTrue determines if an expression is true.

    1. True
    2. False


  1. The assertTrue method is one of numerous assertion methods in the JUnit framework. Find out what the others are.

Programming Exercises

  1. Complete the following:
    1. Complete the VectorTest class. You can find out what other public methods the Vector class has by checking the API.
    2. Add another test case to the example in this chapter to test the java.util.Properties class.
    3. Write some unit tests for the project you are currently working on.
    4. On your next project, try the test - code - design cycle.