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

Import

And click next

Select Archive File Option and select the TeaMaker.zip file

Import ProjectThen 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.

New Folder

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.

File structure

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.

Build Path2. Select the Add Library… button to the right of the window. Select JUnit from the library list, and press the Next > button.

Add JUnit Library

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.

Add JUnit Library4. Add the newly created unittests folder to the Java build path by clicking on Source tab and “Add Folder” button.

Build Path Source5. Add the newly created unittests folder to the Java build path by clicking on Source tab and “Add Folder” button.

Source Folder Selection

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.

JUnit Test Case

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

Test Method

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

Writing test cases

2. Setup the member variables and do the initializations

Setup Member variables

3. Write code to test AddInventory

Write Test code

4. Write code to test AddInventoryException

Write test code

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.

Run test cases

Write code to test MakeTea method

makeTea test case

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(condition)
  • assertFalse(message, condition)
  • assertNotNull(object)
  • assertNotNull(message, object)
  • assertNotSame(expected, actual)
  • assertNotSame(message, expected, actual)
  • assertNull(object)
  • assertNull(message, object)
  • assertSame(expected, actual)
  • assertSame(message, expected, actual)
  • assertTrue(condition)
  • assertTrue(message, condition)
  • fail()
  • fail(message)

Exercise

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.

Tagged with: EclipseJAVATutorial
 

One Response to Unit Testing in Eclipse IDE (JUnit)

  1. animesh says:

    Awesome article

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

 

Looking for something?

Use the form below to search the site:


Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.