1.0 What is JUnit?
JUnit is an open source unit testing framework for automatically unit testing Java programs. JUnit provides functionality for writing and running unit test cases for a project under development, and is helpful when doing XP. This tutorial describes how to use JUnit within the Eclipse environment. You can quickly create test case and test suite classes to write your test code in. With Eclipse, becomes very easy to organize and implement your code and test cases. Typically, you create the application class that you want to test first. Then a tester can create the associated test case which provides a one-to-one correspondence between application classes and test classes. However, a tester can create test classes individually and later tie them to application classes. By using the built in functionality to create JUnit classes, the test cases are created with the needed imports and extensions for JUnit to run. Once the test case class is built the actual test cases are then coded in by the tester.
JUnit test classes can be rolled up to run in a specific order by creating a Test Suite. The code to run the test suite and to add all of the specified test cases you’ve created, is added to the test suite for you. There are two versions of JUnit currently available. JUnit 3.8 uses specific naming conventions for identifying test classes, methods, and suites. These naming conventions are described below:
- Test Case Class: Named [classname]Test.java, where classname is the name of the class that is being tested.
- Test Case Method: Named test[methodname], where methodname is the name of the method that is tested.
Import TeaMaker into Eclipse
We will be using the TeaMaker project example throughout this tutorial to highlight the main features of JUnit. TeaMaker is a small application that simulates the functionality of a Tea maker.
Download the TeaMaker.zip package before starting this tutorial.
Select File -> Import -> Existing Projects into Workspace
And click next
Select Archive File Option and select the TeaMaker.zip file
Then click finish
TeaMaker File Structure
It is considered a best practice in testing, to separate the test case code from the application code. Typically the application code is in a source folder called src/ while the test code is in a source folder called unittests/ or tests/. Therefore you should create a folder called unittests in the main tree.
Below is the file structure for the TeaMaker example that is used for as the exercise in this tutorial. You can emulate this file structure in your other Eclipse projects.
Most projects that you create will have a src/ folder that contain the main application code, a bin/ (which is not shown in the Package Explorer view) folder that contains the compiled .class files, and a lib/ folder that contains jar files that need to be on the project’s build path. To run JUnit test cases the JUnit libraries must be on the classpath. JUnit 3.8 and JUnit 4 are integrated with Eclipse; therefore, we can add the Eclipse provided libraries to the project.
Putting JUnit libraries on the Project Classpath
The JUnit library is required to be on the project classpath to compile and run the JUnit test cases. The classpath may be specific to the computer that you are on, so check to make sure that the JUnit library is set up correctly. If your JUnit library isn’t set up correctly, there will be an warning message at the top of the Java Build Path window.
1. Right click on the project and select Properties. In the left column select Java Build Path and select the Libraries tab.
2. Select the Add Library… button to the right of the window. Select JUnit from the library list, and press the Next > button.
3. Use the drop down box to select the version of JUnit that you want to use for your project. We are using JUnit 3 for the TeaMaker example in this tutorial. The location of your JUnit 3 library may vary from the one pictured below.
4. Add the newly created unittests folder to the Java build path by clicking on Source tab and “Add Folder” button.
5. Add the newly created unittests folder to the Java build path by clicking on Source tab and “Add Folder” button.
Creating a Test Class
JUnit convention is that there is a test class created for every application class that does not contain GUI code. Usually all paths through each method in a class are tested in a unit test; however, you do not need to test trivial getter and setter methods.
There are many ways to create a JUnit Test Case Class
1. Select File > New > JUnit Test Case
2. Select the arrow of the button in the upper left of the toolbar. Select JUnit Test Case ,
3. Right click on a package in the Package Explorer view in the Java Perspective, and select JUnit Test Case, or
4. Click on the arrow of the icon in the toolbar. Select JUnit Test Case .
5. You can create a normal Java class as shown in the Eclipse tutorial, but include junit.framework.TestCase as the super class of the test class you are creating.
6. Right click on an application class that you want to create a test class for, and select New > JUnit Test Case.
Test Case wizard
The wizard for creating a new JUnit test case classes is displayed in Figure below. If you use the method of creating a JUnit test case presented in step 6, most of the information below will be filled in for you, but may require minor modifications.
1. The source folder specifies where you want to create the test case. Based on the project hierarchy presented in Figure 1, we want to create the new test case in the unittests/ source folder.
2. Next, specify the package you want your test case to belong to. If you are associating your test case with an application class, then you will want both of these classes to share the same package so you can take advantage of package level visibility when testing your application class.
3. Specify the test case name. If you are associating your test case with an application class the convention is that the test case name is the application class name followed by Test.
4. JUnit has several standard methods that are useful for testing. setUp() and tearDown() methods are run before and after each test method.
5. If you are associating your test case with an application class, then Browse for the application class in the Class under test field.
Test case methods
If you selected a Class under test you can click the Next button to select which methods you want to write test cases for. The method signatures will be created for you.
Click on Next and select AddRecipe, deleteRecipe, addInventory and makeTea test method stubs to create
Click Finish and the new test case class will open in the editor.
Writing JUnit Test Cases
1. Add the following member variables in the beginning of the class
2. Setup the member variables and do the initializations
3. Write code to test AddInventory
4. Write code to test AddInventoryException
Running JUnit Test Cases
The goal when running JUnit test cases is a green bar in the JUnit view. The green bar shows that all of the test cases passed. A red bar shows that one or more of the test cases failed. The stack trace of a test failure or error are displayed below the listing of the test cases run. Figures show the green and red bars in the JUnit view.
Write code to test MakeTea method
Assertion Statement Reference
In JUnit, a test occurs when ever you assert that something should be a specific value. Each JUnit test case (method) should have at least one of the assert statements listed below, otherwise the test passes, which can be misleading if you never actually check the value of any data. The most common assert statement is assertEquals() which takes at least two arguments. The first argument is the expected value of some piece of data at that point in the test case. The second argument is the actual value of that data, usually obtained by a method call, at that point in the test case. The method will check for equality between the two pieces of data. For a custom object this means that the equals() and hashCode() methods should be overridden. Otherwise, the assertEquals() method will check for equality of the objects location in memory. These will be different because the expected object is created within the test case while the actual object is created within the application. If any of your assert statement fail, the test progress bar in the JUnit view will be red. Additionally, a failing assert statement will cease execution for that test case. Therefore, assert statements after that point will not be executed. This is a list of the different types of assertion statements that are used to test your code. Any Java data type or object can be used in the statement. These assertions are taken from the JUnit API.
- assertEquals(expected, actual)
- assertEquals(message, expected, actual)
- assertEquals(expected, actual, delta) – used on doubles or floats, where delta is the difference in precision
- assertEquals(message, expected, actual, delta) – used on doubles or floats, where delta is the difference in precision
- assertFalse(message, condition)
- assertNotNull(message, object)
- assertNotSame(expected, actual)
- assertNotSame(message, expected, actual)
- assertNull(message, object)
- assertSame(expected, actual)
- assertSame(message, expected, actual)
- assertTrue(message, condition)
The TeaMaker code is complete; however, you can create and run unit tests on the following user stories:
1) Add a Recipe
2) Delete a Recipe
3) Edit a Recipe
4) Add Inventory
5) Check Inventory
6) Purchase Tea.
One test class has been created for you: TeaMakerTest under the unittests/ directory. You can create RecipeTest and InventoryTest classes as well. There are currently 5 (very obvious) bugs in the system. You need to generate enough unit tests to find 2 of the 5 bugs.
- Eclipse IDE Tutorial for Java Programmers
- Version Control with Subversion in Eclipse IDE
- Learn to use Design Patterns
- Advanced Java Tutorial (For Intermediate)
- Java Tutorial for Beginners
- J2EE Tutorial
- Java Logging – Log4j
- Data Structures Tutorial using C++
- Advanced Data Structures Tutorial using C++
- Difference between Java Application and Java Applet
- C++ Tutorial for Intermediate Programmer
- Zodiac Signs Program in C++ and Java
Popular Posts (last 30 days)
- Circular Linked Lists 1300 view(s)
- Attendance Management Sys… 1065 view(s)
- Applications of Stack in … 1058 view(s)
- Graph Implementation in C… 904 view(s)
- Implementing Stack Data S… 775 view(s)
- Simple Currency Converter… 661 view(s)
- GRASP Design Patterns 501 view(s)
- Recursive Factorial funct… 490 view(s)
- Finding Minimum, Maximum … 364 view(s)
- Implementation of Priorit… 310 view(s)
TagsAndroid C-Sharp C/C++ language Classes Data structures Design Pattern Eclipse Game Development Graphics Design Books HTML iPhone JAVA JAVA GUI MIPS Assembly Mobile Programming Books Object Oriented PDF PHP Programming Programming Books Programming Languages Books Python RaphaelJS REST Source Code Threads Tutorial Web Development Books