Test Driven Development
With JUnit & Eclipse

Since December, 2005, I produced an early version of this page.
That early verison is now (24 December 2007) seriously obsolete.


"Never in the field of software development was so much owed by so many to so few lines of code." Martin Fowler in reference to the JUnit Project.

On February 22, 2006, Java Developer's Journal announced that Parasoft Jtest won InfoWorld's 2006 Technology of the Year Award. JTest "automatically generates and executes JUnit tests for instant verification, and allows users to extend these tests." The white paper, Applying a Java Testing Framework [pdf], retrieved from Enerjy Software Integrity on 20 October 2006, provides an interesting discussion of the merits of using unit testing generally and JUnit Testing in Java specifically.

Latest Version of JUnit

This page was initially created when the latest version of JUnit was JUnit3.8.1.

By 28 October 2007 JUnit 4.5 had been released. Students are advised to use the latest stable version of JUnit available.

The home of JUnit will be found at http://www.junit.org/

The latest stand alone release (4.5) at time of writing will be found at the sourceforge.net site.

On 28 October 2007, a recent excellent tutorial that students using Eclipse should study is:

Java Unit Testing With JUnit 4.x in Eclipse
[web-html] [web-pdf] [csg-html] [csg-pdf]

Students may wish to view the North Carolina State University tutorial Unit Testing in Eclipse Using JUnit. All of the NCSU tutorials are excellent. Note, however, that this tutorial addresses the older version JUnit 3.8.1.


JUnit Regression Testing

TaskTopicAssignments

1

Regression Testing

The selective retesting of a software system that has been modified to ensure that any bugs have been fixed and that no other previously working functions have failed as a result of the reparations and that newly added features have not created problems with previous versions of the software. Also referred to as verification testing, regression testing is initiated after a programmer has attempted to fix a recognized problem or has added source code to a program that may have inadvertently introduced errors. It is a quality control measure to ensure that the newly modified code still complies with its specified requirements and that unmodified code has not been affected by the maintenance activity.

- Regression Testing. Retrieved January 8th, 2006, from Wěbopēdia

So What's The Big Deal?

Click here to find out.

The great value of a paradigm in the study of a discipline like Computer Science at the high school level is the scope of it's transference. To implement JUnit Testing in designing and building a Java program is to implement one of the most elegant, powerful paradigms in the social and physical sciences. Whatever your future career, this lesson is relevant!

TaskTopicAssignments

2

JUnit Testing
with OLD VERSION
JUnit 3.8.1

JUnit JavaDocs Overview

JUnit JavaDocs Tree View

JUnit JavaDocs Index

JUnit Source Code

JUnit Yahoo Group

Junit Executable Zip file

Incorporate JUnit Testing into the IB Dossier in sections:

A2 Criterion For Success
A3 Prototype Solution
D2 Evaluation Solutions

Unit Testing Summary

JUnit Testing with OLD VERSION JUnit 3.8.1

This is an excellent introduction to JUnit, albeit an older version. I will include it for now until I can provide a comparable overview of the current version ... which may never happen.

  1. Download the latest version of JUnit. It is a zipped file. Unzipping the file dumps a folder with a name such as "junit3.8.1". The folder contains:

    README.html  explains contents of downloaded folder & contains links to
    articles that introduce and explain how to implement JUnit.
    junit.jar  a jar file with the JUnit framework and tools
    src.jar  a jar file with the source code of the junit framework
    junit  the source code of the JUnit samples
    samples  sample test cases
    tests  test cases for JUnit itself
    javadoc  javadoc generated documentation
    doc  documentation and accompanying articles

  2. Place both the junit folder and the junit.jar file in a java related folder, but NOT in the the extension directory of your JDK installation. Watch out. Messing up here means that NOTHING will work!

    This crucial step assumes that you understand how to configure a Windows working environment. Read the two page explanation by Ashley Mills, Univeristy of Birminham: Configuring A Windows Working Environment.

    Better explanations in using classpath are found at Java Notes and Java Glossary.

    For example, if you downloaded a junit.zip file and unstalled it to a directory called junit3.8.1, and the path to that junit happened to be c:\Program Files\junit3.8.1, then you would place the following paths in your classpath environmental variable.

    • c:\Program Files\junit3.8.1\junit
    • c:\Program Files\junit3.8.1\junit.jar

    Remember: Do NOT install the junit folder in a JDK directory! Put it somewhere ... anywhere ... else.

    To add paths to the classpath in Windows XP, click: Start --> Control Panel --> System --> Advanced --> Environment Variables --> CLASSPATH --> Edit. There is a classpath variable in both the upper and lower windows of the Environment Variables dialog box. You edit the local variables window, (the upper window of XP's Environment Variables dialog box), not the system window (the lower window of XP's Environment Variables dialog box).

TaskTopicAssignments

3

JUnit Testing
with NEW VERSION
JUnit 4.4

Incorporate JUnit Testing into the IB Dossier in sections:

A2 Criterion For Success
A3 Prototype Solution
D2 Evaluation Solutions

Unit Testing Summary

JUnit Testing
with NEW VERSION
JUnit 4.4

  1. You will use JUnit version 4+ which requires Java 5 or later. Therefore set compiler compliance to SDK 5 or later after Window → Preferences → Plus sign "+" beside "Java" → Compiler → find "Compiler Compliance Level" → Choose 5.0 or later from the drop down menu.

  2. Add the JUnit files to the Eclipse classpath: File → New → JUnit Test Case → Click the radio button for "New JUnit 4 Test" → Near the bottom it says, "JUnit 4 is not on the build path of Project ?whatever? Click here to add JUnit 4 to the build path and open the build path dialog." → Click on the link "Click here" → Click the plus sign "+" beside "JUnit 4" → Select by clicking "junit.jar-...\eclipse\plugins\org.junit4...." → OK.

  3. Now learn to use JUnit Testing with Eclipse by following a tutorial such as Java Unit testing with JUnit 4.x in Eclipse - Tutorial by Lars Vogel, beginning with his example class, MyFirstJUnitTest.

  4. Ignore this if you wish, but the latest version of JUnit on 24 December 2007 was JUnit 4.5. A jar file containing a snapshot of the JUnit 4.5 files can be downloaded from here. [A jar file is a java specific compressed "zip" file. The word "jar" stands for "Java Archival". A "snapshot" of files is a collection of files.]

  5. Ignore this if you wish, but release notes for versions JUnit 4.4 and 4.5 will be found at http://junit.sourceforge.net/doc/ReleaseNotes4.4.html.

TaskTopicAssignments

4

New
JUnit 4
Features

Get Acquainted with the New Advanced Features of JUnit 4

Read this article and play with the code. It compares features of the JUnit version 3.8 with those of JUnit version 4.

Some of the new features were made possible by innovations in Java 5 such as autoboxing. It is thus worthwhile remembering that versions of JUnit 4 and later will not work on versions of Java prior to Java 5.

Topic

Assignments

Test-Driven Development

Shortcut To Print To Console:   Enter the "stuff" to be printed. → Highlight "stuff" with the mouse. → <Ctrl-Space> → <Up-Arrow> → <Enter> → Eclipse surrounds the "stuff" with System.out.println( ).

To create a separate testing folder to isolate JUnit testing code from application code:   File → New → Source Folder → Folder Name: test → Finish. This avoids deploying testing code with an application.

To create a JUnit package containing the same name as the application package being tested:   Select ("highlight") the name of the testing folder in the package view → File → New → Package → Type the same name as the source code package. (Both the application and testing package have the same names.) → Finish.

To create a JUnit test class:   Right mouse click the testing package → New → Other → JUnit → JUnit Test Case → Type name of testing class == name of class to be test followed by "Test" (eg: "BeHappyTest") → Place desired ✓s for method stubs → Finish → Finish.

To create a JUnit test suite:   Highlight the testing package. → Right mouse click → New → Other → JUnit → JUnit Test Suite → Next → Place desired ✓s → Finish. This creates a single-button test for an entire application!

Names of all JUnit testing methods begin with "test..."

Variable name that is italicized is a static variable.

To open a new Java Scrapbook Page:   File → New → Other.... → Select Java → Java Run/Debug → Scrapbook Page. → Click Next. Don't forget to later select ("highlight") the code before clicking the "inspect" button.

To automatically generate accessor &/or mutator methods:   Source → Generate Getters and Setters... → Place desired ✓s → OK.

Quick Fix:   <Ctrl><1> ( ie: Control-One ) OR Click on the light bulb. The Java editor offers corrections for most problems underlined with a problem highlight line. For example, use in a testing class to create method stubs in the class being tested.

TODO Comment:   // TODO tada tada tada
(No space between "TO" and "DO") Eclipse maintains a task "ToDo" list for you. Window → Show View → Tasks.

Comment a section of code:   Highlight the section of code → <Ctrl>< / > Toggling <Ctrl>< / > "uncomments" commented code.

To provide package access to a class member:   Remove all scope modifiers. Scope modifiers are private, public and protected.

To convert a local variable to an instance variable (ie: instance "field"):   Select a declaration or a reference to a local variable → Refactor → Convert Local Variable to Field... → Select access modifier → Select location for initialization → Select whether field is to be static → Select whether field is to be final (ie: a constant) → OK

To automatically extract a method from a block of code:   Highlight the lines → Refactor → Extract Method... → Type methodName → OK Same blocks of code throughout the class are replaced by the method call!

To automatically create a public method template:   Type "pub" (initial three letters of "public") → <Ctrl-Space> → Select "Public_method - public method" → Type "void" or other return type → Enter → Tab → Type "testToString" or other name of method Do a similar process for a private method template.

To automatically create the public static void main( String[ ] args ) template:   Type "main" → <Ctrl-Space> → Press <Enter> This is the point in Java where execution of the program begins.

To automatically create an assertEquals( expected, actual) call:   Type "asserte" (initial letters of "assertEquals...") → <Ctrl-Space> → Press Enter → Type "Smith" or other string → Enter → Tab → Type b2.toString() or other string reference call → Type a semicolon to end the statement Do a similar process for other standard method calls.

Test-Driven Development
  1. Think about what the method should do.
  2. Write a test case that will test this method.
  3. Write the new method.
  4. Test the new method.
  5. When it passes ... we're done!

... the unit tests document the program without the need to maintain separate written documentation that can easily become out of date.

Mark Dexter, Using Test-First Development


Follow and implement the lessons and activities of Mark Dexter's sixteen 15-minute tutorials of Eclipse And Java For Total Beginners [csg] [web]

Toggle <F11> to switch between IE's normal and full screen views.

Toggle <Alt-Tab> to switch to your last application, as between Eclipse (program development) and Internet Explorer (tutorial).

Preserve the project at the end of each tutorial. To do this, create a new project at the beginning of each tutorial and import the project from the end of the last tutorial into a the new tutorial's project. Projects can be called TB1, TB2 .... (TB == Total Beginner)

Refer to this Tutorial Companion Guide [pdf].

Beware This GOTCHYA: The tutorial code refers to an object "ml" of a class "MyLibrary". The "ml" is "m" followed by the letter "l" (pronounced "el"), not the digit "1" (one).

  1. Create Your First Class
  2. Add Methods to Class
  3. Use Eclipse Scrapbook
  4. JUnit: Create Test Class
  5. JUnit: Create Test Methods
  6. Using Test-First Development
  7. Create Book Class
  8. Add Person to Book Class
  9. MyLibrary Class and ArrayList
  10. Start on MyLibrary Class
  11. Create first methods in MyLibrary class
  12. Create checkOut( ), checkIn( ) Methods
  13. Continue checkOut( ) Method
  14. Finish checkOut( ) Method
  15. Finish MyLibrary Methods
  16. Create main( ) Method and JAR File

For the final code, including all application and testing code, submit a printed copy of a wordprocessing document containing:

  1. Footer
  2. BIG JAVA's Formatting Style by importing UBC's file.
  3. Identification Template
  4. Screen Dump(s)
  5. HTML Javadoc files including the standard tags @author, @version, @param, @return and the customized tags @invariant, @pre and @post
  6. Print on both sides of a sheet of paper, two pages per side = = four pages per sheet of paper. See Make Hard Copy of Source Code.
  7. Prepare a JAR file of the final code following Tutorial #16.

To create an executable JAR file:   [ Hint: First save the path to your project so you can later paste it as the destination location of your executable JAR file → Right mouse click name of project → Properties → Select ("highlight") the location (eg: "H:\TotalBeginnerProjects\TB11") → Copy with → Cancel ] File → Java → JAR file → Next > → Select by checking ✓ only the #src directory → Select a directory to save the JAR file in → Give the JAR file a name (eg: mylibrary.jar) → Next > → Tell Eclipse which class has the main() method (Click the "Browse..." button.) → Finish    JAR == Java ARchival File. An executable JAR file will execute on any system that has a JRE (Java Runtime Engine) installed. Selecting only the #src directory allows us to now easily exclude the bundling of testing code with the application.

To check the run of your JAR file from the command line prompt:   Copy the path of your JAR file location: Right mouse click name of JAR file → Properties → Select ("highlight") the location sans name of file (eg: "H:\TotalBeginnerProjects\TB16") → Copy with <Ctrl-C> → OK ] → [ Note: In order for the JAR file to "automatically" execute at the command line prompt, the O/S environmental path variable must be contain the path to Java's jar.exe file. An example of the location of a jar.exe file is: C:\Program Files\Java\jdk1.6.0_01\bin.] → Start → Run... → Type cmd in the Open dialog window → A command prompt window (aka DOS window) opens → On the prompt line, type the drive location of the file (eg: "H:) → Press <Enter> → The prompt now reflects the root of the drive where the JAR file is located ( eg: H:\> ) → On the prompt line, type "cd" (stands for "change directory") → Press the space bar once. → Right mouse click the title bar. → Edit → Paste → The prompt line should now include the path of the JAR file. [ eg: H:\TotalBeginnerProjects\TB15\TB16> ] → Type "dir" to call the directory → You should now see the jar file. → At the command line, type "java -jar followed by the name of the jar file. [ eg: java -jar mylibrary.jar ] → Press <Enter> → The JAR file should now execute.

Create A "New" Project From An Existing Project

These are really "backups of prior stages" of a single, cumulative project. It would be tragic if, upon experiencing a "bug" during tutorial #12 that could not be corrected, you had to redo all eleven prior tutorials in order to continue the project. Taking a few moments at the beginning of each new stage of the project (each new tutorial) ensures that you always have a "last good stage" that is only one tutorial away. This also facilitates later review of code of a specific tutorial at that particular stage of development.

  1. Create a new project:   File → New → Project.. → Java → Java Project → Next → Project Name: TB12 → Create new project in workspace → Select a JRE (Java Runtime Environment) → Select Project layout → Finish

  2. Copy path of location of source project:   Right mouse click name of project → Properties → Select ("highlight") the location (eg: "H:\TotalBeginnerProjects\TB11") → Copy with <Ctrl-C> → Cancel

  3. Open the Import Wizard:   Select ("highlight") name of new project → From the main menu bar, select File → Import....

  4. Select Type of Resources To Import:   General → File System → Next.

  5. Specify Path and Files To Import:   Identify source directory as the "From directory:" → Paste <Ctrl-V> location of the source project (eg: "H:\TotalBeginnerProjects\TB11") → Click the "Browse..." button → The "Import from directory" dialog box appears with name of source folder → Click "OK" → Click the "Select All" button → Type name of "Into folder" (existing destination folder) if it is not already there. → Check ✓ "Overwrite existing resources without warning" → Select "Create selected folders only" → Finish

Topic

Assignments

Test-Driven Development: Persistence

Persistence is a way to store the state of a program when the computer is turned off. [ Lesson 01 ]

JAR files are compressed files of related packages. [ Lesson 06 ]

The Manifest.MF file contains information about the other files packaged in a JAR file. If the JRE needs to get any class files from a different JAR file, this information needs to be added to the manifest manually. [ Lesson 10 ]

Clicking on the name of a method in Package Explorer opens that method in the Editor Window. [ Lesson 10 ]

To navigate back & forth:   back == <Alt><Left-Arrow> → forward == <Alt><Right-Arrow> [ Lesson 06 ]

To compare historically different versions of a file:   Right click on file → Compare With → Local History... Allows restoration of prior versions as needed. Control versions of history of files:   Window → Preferences → General → Workspace → Local History [ Lesson 09 ]

To create a zip archive file of one or more projects:   File → Export... → General → Archive File → Next > → Select project(s) to export → To archive file: h:\td\myZip.zip → Finish. Use these to deploy projects and to take a "snapshot" of a project. [ Lesson 01 ]

Always use finally to close files, so it always happens, whether or not there is an error. [ Lesson 01 ]

Use the Launch Configuration Dialog to switch from JUnit 3 to Junit 4:   Run → Open Run Dialog... → change from JUnit 3 to JUnit 4 thus → Test runner: JUnit 4 → Apply → Run This runs testing units using JUnit 4. [ Lesson 02 ]

To tell JUnit 4 that a method is a test method:   Precede the method signature with the tag @Test ( eg: @Test public void saveToXMLFile( ) ) [ Lesson 08 ]

To get objects from XML files:   Convert the object to an XML string with method: convertToXML( ) → Save string to text file with method: saveStringToFile( ) [ Lesson 02 ]

To save objects to XML files:   Read XML string from a text file with method: getStringFromFile( ) → Convert XML string to object with method: convertFromXML( ) [ Lesson 02 ]

Static methods are owned by a class and not an instance of the class, like functions in procedural programming languages. [ Lesson 02 ]

Use the menu to switch from JUnit 3 to Junit 4:   Select the JUnit 3 folder → Right mouse click → Configure... → Select JUnit library version JUnit 4 → Finish The JUnit 4 package is backward compatible. This selects the version to support.

FileWriter(fileName) only writes one character at a time, so we improve performance by "buffering" a block of fileName characters into large chunks of data by passing FileWriter objects into the BufferedWriter(FileWriter) constructor. Use syntax: BufferedWriter( new FileWriter(fileName) ) [ Lesson 04 ]

FileReader(fileName) only reads one character at a time, so we improve performance by "buffering" a block of fileName characters into large chunks of data by passing FileReader objects into the BufferedReader(FileReader) constructor. Use syntax: BufferedReader( new FileReader(fileName) ) [ Lesson 05 ]

The class StringBuilder is like string but it is optimized for concatenating and appending strings., [ Lesson 05 ]

The method BufferedReader.readLine( ) automatically keeps track of it's position in the file, so it reads each line sequentially. [ Lesson 05 ]

When a cursor is beside a parenthesis, <Ctrl><Shift><P> moves the cursor to it's matching parenthesis. [ Lesson 05 ]

To add JAR files to a project ( Allows import of packages in the JAR file ) :   Select Project → Project → Properties → Java Build Path → Libraries tab → Add Exertal JARs... → Browse to folder holding the JAR file → Select the JAR file → Open → Observe that JAR file has been added to the project → OK [ Lesson 06 ]

To attach JDK Java source code of Java language classes (String, ArrayList, BufferedReader, etc) to a project:   Select Project → Project → Properties → Java Build Path → Libraries tab → Find "JRE System Library [jre 1.6.0_03]" or such → Expand (click the plus "+" key) the JRE System Library → Expand rt.jar → Select "source attachment: (None)" → Edit... → External File... (Looking for "src.zip") → Browse to location of JDK (eg: Java\jdk1.6.0_03 → Select "src.zip" → Open → OK → OK [ Lesson 06 ]

To view source code of Java language classes:   Attach JDK Java source code to the project (see above) → Open a class in the project → Select a class name (for example) "String" → Navigate → Open Declaration (F3) → This opens the String class Java source file → or try Navigate → Open Type Hierarchy (F4) → Inspect any members (fields and methods) of the String (or other) class. [ Lesson 06 ]

To open the history view of a file:   Window → Show View → Other... → Expand Team → History → OK → View History → Continue to compare versions → To Compare an historical version with the "local" version:   History Tab → Click on one of the "Revision Times" → Right click Compare Current with Local → Note upper screen shows differences in structureNote lower screens show differences in actual code. [ Lesson 10 ]

Manifest.MF   Text   File   ( Save in Project as manifest.txt )   [ Lesson 10 ]
Manifest StatementPurpose
Manifest-Version: 1.0Always begin with this version number.
Main-Class: org.persistence.tutorial.MyLibraryPath to file containing the main method.
Class-Path: xstream-1.2.2.jarOther JAR files containing needed classes.

To create an executable JAR file:   [ Hint: First save the path to your project so you can later paste it as the destination location of your executable JAR file. ] → File → Export... → Java → JAR File → Next > → Select only src folders → Select export destination path for the JAR file ( eg: F:\ws\TB\PER10\persistence.jar ) → Next > → Check the two check boxes for exporting class files with compile errors and warnings → Next > → Select "Use existing manifest from workspace" → Browse to find the manifest files ( eg /PER10/manifest.txt ) → Finish [ Lesson 10 ]

To run a JAR file outside of Eclipse:   Place both JAR files [ persistence.jar & Xstream-1.2.2.jar ] in the same directory → Start → Run... → Open: cmd → This opens the Windows System Console. → On the prompt line, type the drive location of the file (eg: "H:) → Press <Enter> → The prompt now reflects the root of the drive where the JAR file is located ( eg: H:\> ) → On the prompt line, type "cd" (stands for "change directory") → Press the space bar once. → Right mouse click the title bar. → Edit → Paste → The prompt line should now include the path to the JAR files. [ eg: H:\TB\PER10> ] → Type "dir" to call the directory → You should now see the two jar files. → At the command line, type "java -jar followed by the name of the primaryjar file. [ eg: java -jar persistence.jar ] → Press <Enter> → You should now see the same output that we saw in the Eclipse Console Window. → Type "exit" at the console prompt and press <Enter> to close the Console Window. [ Lesson 10 ]

Test-Driven Development: Persistence
  1. Think about what the method should do.
  2. Write a test case that will test this method.
  3. Write the new method.
  4. Test the new method.
  5. When it passes ... we're done!

Follow and implement the lessons and activities of Mark Dexter's twelve 15-minute tutorials of Eclipse And Java: Introducing Persistence [csg] [web]

Toggle <F11> to switch between IE's normal and full screen views.

Toggle <Alt-Tab> to switch to your last application, as between Eclipse (program development) and Internet Explorer (tutorial).

Create a project at the end of each tutorial by importing the project achieved by the end of the last tutorial. Name projects after each tutorial: PER01, PER02 ... (PER == Persistence).

Refer to this Tutorial Companion Guide [pdf].

Beware This GOTCHYA: The tutorial code refers to an object "ml" of a class "MyLibrary". The "ml" is "m" followed by the letter "l" (pronounced "el"), not the digit "1" (one).

Import this project to begin the first lesson. See how to Create A "New" Project From An Existing Project.
  1. Persistence with XML & Serialization [End Prj 01]
    Use try ... catch ... finally blocks.

  2. Converting form JUnit3 to JUnit4 [End Prj 02]

  3. saveStringToFile() & getStringFromFile() Methods [End Prj 03]

  4. Writing Data To Disk (BufferedWriter & FileWriter Classes) [End Prj 04]

  5. Reading Text Files From Disk (FileReader Class) [End Prj 05]

  6. Using XML Libraries & XML Conversion Methods [End Prj 06] [ XStream web site ] [ XStream Core Only JAR ]

  7. Write Test Methods that Test the Convert Methods [End Prj 07]

  8. Write XML Convert Methods [End Prj 08]

  9. History View of Files. Writing Methods in XML [End Prj 09]

  10. Using Eclipse's History View With Java Source Files [End Prj 10]

  11. Object Serialization in Java

  12. Add Serializable Interface & SerialVersionUID Field


For the final code, including all application and testing code, submit a printed copy of a wordprocessing document containing:

  1. Footer
  2. BIG JAVA's Formatting Style by importing UBC's file.
  3. Identification Template
  4. Screen Dump(s)
  5. HTML Javadoc files including the standard tags @author, @version, @param, @return and the customized tags @invariant, @pre and @post
  6. Print on both sides of a sheet of paper, two pages per side = = four pages per sheet of paper. See Make Hard Copy of Source Code.
  7. Prepare a JAR file of the final code following Tutorial #12.

URL:   http://www.comscigate.com/    Last Revised:  December 31, 2007