"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: [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 |
|||||||||||||||||||||||||||||||||
| Task | Topic | Assignments | |||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
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. |
|||||||||||||||||||||||||||||||
So What's The Big Deal? |
|||||||||||||||||||||||||||||||||
|
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! |
|||||||||||||||||||||||||||||||||
| Task | Topic | Assignments | |||||||||||||||||||||||||||||||
2 |
JUnit Testing
|
||||||||||||||||||||||||||||||||
|
Incorporate JUnit Testing into the IB Dossier in sections:
|
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.
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 |
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.
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).
|
Incorporate JUnit Testing into the IB Dossier in sections:
|
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.
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.
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.]
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.
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 DevelopmentShortcut 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 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. |
For the final code, including all application and testing code, submit a printed copy of a wordprocessing document containing:
| |||
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
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.
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.
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
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
Open the Import Wizard: Select ("highlight") name of new project → From the main menu bar, select File → Import....
Select Type of Resources To Import: General → File System → Next.
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: PersistencePersistence 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 structure → Note lower screens show differences in actual code. [ Lesson 10 ]
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 ] |
|
|||||||||||||