Alvin Bunk

Alvin's Blog.

JUnit Tutorial

JUnit is a unit testing framework for testing Java applications. It’s been around for a long time and therefore is is widely used.

In order to use JUnit in Eclipse, you simply need to create a Java Project, create a package, add a class file, and then then add a “JUnit Test Case”. Let’s step through that.

First start up Eclipse. In these screen shots I’m using 32bit Eclipse Juno (because I’m also working with JBoss), however this shouldn’t matter much. By the way, if you haven’t used Eclipse IDE before, what are you waiting for?

Once Eclipse starts, select “File > New > Java Project“. The Dialog box “New Java Project” appears like the screenshot below. Set the project name to “JUnit Test Project“.

New Java Project

Click “Next >” to continue. We need to add a source folder called “test” where we will store all the JUnit files. Click the “Create new source folder” and enter a folder name of “test”, then click “Finish“. The dialog box will look like the image below (that is before you click Finish).

JUnit Folders

Now in Eclipse you should see the project open in the “Package Explorer” window with two source folders shown, namely “src” (for source files) and “test” (for the JUnit test files).

Here comes the important part: We need to add a Java class with enough complexity to test at a number of the JUnit methods. Here is a link to the JUnit API; If you open it, go to the package “org.junit”. You will find this documentation very useful when you are writing test classes/methods. What I will do in my example is create a class that creates a int array, and has various methods (such as add remove, so on…) that can be used. My idea for this came from another tutorial written by Daniel but didn’t explain how to create the class file.

Before we actually add the class, we should create a package. Using packages allows us to put files in different folders. The reason we might do this is for example source code files are unrelated to test (as in JUnit test) files. When naming a package, we should use the proper naming conventions. Most organizations use their company’s domain name. Take a look at the link [] for more detailed information about package naming. Since this example code is my own, I’ll use “com.wordpress.alvinbunk” as the package name. This should not clash with anything.

In Eclipse, right-click on the “src” folder and select “New > Package“. The “New Java Package” dialog box opens. Enter the name as “com.wordpress.alvinbunk” (or whatever you plan to use). The dialog should appear like the screenshot below.

JUnit Package Name

Click “Finish” to create the package. Now do the same thing in the “test” folder this time and add a package called “com.wordpress.alvinbunk” to that folder.

Let’s now create the int array class, so right click on the package “com.wordpress.alvinbunk” under the “src” folder, and select “New > Class”. Then enter a “Name” for the class of “IntArray” (for lack of a better name). The “New Java Class” dialog box should look like the image below.

JUnit Java Class

Then click “Finish” to create the class. This creates a skeleton IntArray class, and we just need to add variables, implement a constructor, and add methods so that we can use this class in our JUnit tests. The image below shows a shrunk down view of the Eclipse IDE showing the skeleton code and plus on the left in the Package Explorer you can see the “JUnit Test Project” and the expanded folders with packages and the single class file just created.

JUnit IntArray Screenshot

First we need to add class variables. We should create a int array which is used to store all the integers. We also need a counter that increases when we add items, and decreases when we remove items. And then one more variable to keep track if the array is empty or not. Add the following lines of code to the class file as shown below.

Now let’s create the constructor. We need to create an array of a fixed size, since I’m not planning on creating a dynamically growing array (that would be too much for this tutorial). So the constructor will set the size, set the counter to “-1” (to indicate the array is empty), and set the isEmpty boolean to true (indicating array is empty). Add the code shown below to the file.

JUnit Constructor

The next things we will add are methods to add and remove integers to the array. You’ll soon see by looking at the code that I don’t actually add or remove anything, and this is because the array is not dynamic. Each time we add an item, it goes into the next position in the array and the counter gets incremented. Also if the array was previously empty, once we add something it is no longer empty. When e remove, we remove from the last index of the array and decrement the counter, and once we’ve remove the last item we set the isEmpty boolen to true. Add the following code to the file.

JUnit Add_Remove

Do you notice any problems with the above code? The first thing is, we are not really removing or adding to the array, but instead merely setting the int value at the index value of the array. I mentioned this point above, since I wanted to make this simple in order to just show how JUnit works, I intentionally made the array a fixed size so that it cannot be grown or shrunk. I’m just using the counter to indicate the size of the array. If you really wanted to create a dynamic array, don’t do it this way!

Secondly, if we use the “add()” method and we’ve exceeded the size of the array, the “add()” method will fail. So in reality, before you call the add method, you need to call the “size()” method (we’ll create this shortly) to determine the size of the array and if it is already full. So you may now be coming to the understanding of why we need JUnit to perform unit tests on software!

Thirdly, the same applies for the “remove()” method. If we try to remove and the array is already empty, then the remove method will fail. We need to check the boolean isEmpty to see if the array is empty before calling remove.

Fourthly, when we remove, we don’t actually remove anything but instead set the value to “0”. Which in reality is not empty, but our counter has decremented.

Now we add two more methods to get the size of the array and whether the array is empty. Add the following lines below the “remove()” method.

// Get array size (zero based).
public int size() {
	return counter;
// Is the array empty.
public boolean isEmpty() {
	return isEmpty;

You can see from the above that the size of the array is simply the value of counter. Next we add a method to get a integer value at a location, and a method to check if the array contains a integer item.

// Get the item at (zero based).
public int get(int location) {
   return arrayInt[location];

// Check if array contains item.
// If array is empty this fails.
public boolean contains(int item) {
   //Declare false unless item exists.
   boolean results = false;
   for(int i=0; i<=counter; i++) {
      if(arrayInt[i] == item) {
         results = true;
   return results;

We are now done writing the code for the class. The Eclipse IDE should show the class file like shown below with the Outline view showing the elements of the class. We are now ready to create a JUnit Test Case file.

To create a JUnit Test Case, right-click on the “” file in the “src” folder and select “New > JUnit Test Case”Note: If “JUnit Test Case” doesn’t appear under “New”, then select “New > Other“, and then browse to “Java > JUnit > JUnit Test Case“. The “New JUnit Test Case” dialog appears. Note that it has the name “IntArrayTest” – We’ll leave that. We want to change the “Source folder” to “JUnit Test Project/test“. See the dialog shot below with the source folder highlighted.

JUnit Test Case

You’ll also notice there is a section about method stubs such as “setUpBeforeClass()”, “tearDown()”, etc… I might not cover these in this tutorial, however, it is important to know what these are used for. Click the “Next >” button to continue.

The “Test Methods” dialog appears. We want to select everything under “IntArray” to test. See the screenshot below for what should be selected.

JUnit Test Methods

Then click “Finish” to create the test case. At this point, Eclipse wil recognize that you need to add JUnit 4 library, and you will see the dialog prompt shown below.

JUnit Library

Simply click “OK” to add the library to the project. The Eclipse IDE creates the file with test stubs created for each method (and constructor) selected previously. Note that each one the test stubs has the code “fail(“Not yet implemented“);” in it. So actually if you ran this in JUnit all these tests would fail.

Now we need to write code to test the constructor and each of the methods. When we write the code, we also need to understand how we expect the code to work and what exactly will happen.

Let’s start with testing the “add()” method. This function basically increments the counter and then sets the int value of the array at the index pointed to by the counter. Also if the array was empty, it sets it to not empty. So let’s add two integers to an array constructed with a size of “4” and then check that it is not empty. Take a look at the screenshot below for the sample code I’ve added.

JUnit testAdd

The code under the “testAdd()”, creates the IntArray then add the two integers “5” then “3” to the array. Then I use JUnit assertFalse to check that the array is NOT empty, and assertEquals to see that position “0” of the array (the first position) contains “5”.

Do you notice a problem with this code? I’m using the methods “isEmpty()” and “get()” to perform tests for the method “add()”! So in other words, it’s a bit of a vicious cycle. If the methods “isEmpty()” and “get()” don’t work, then my “testAdd()” will fail as well. But regardless of that, I will proceed just to show you how JUnit works and we’ll address those later.

To run the JUnit Test Case in Eclipse, right-click on the “” file as select “Run As > JUnit Test“. This opens a JUnit view on the bottom middle of the Eclipse IDE. Here we can see the status of each of the tests with Errors and Failures. See the screenshot below for a sample run of this test.

JUnit testAdd status

Notice the test “testAdd” has a green check mark besides it? That means it passed! Also look at the counts: There are 6 failures and 7 runs. So only one of the tests passed. This is because all of the other test methods have the code “fail(“Not yet implemented“);” in them. Which means they run and return as fail.

You might run into this same problem when you are writing your tests. For example, you may have some code which you have not fully complete, but you don’t want to run it. So how do you handle this? Simple: Add the “@Ignore” annotation. This will ignore any JUnit tests after the @Ignore annotation. Let’s add this just before the “@Test” annotation in front of the “testRemove()” test method. The screenshot is shown below.

JUnit testRemove Ignore

Notice the red squiggly line below “@Ignore”, and also the yellow lightbulb with an “x” on the left by the line number? This is a Eclipse warning that “Ingnore cannot be resolved to a type”. If you move your mouse over the “@Ignore” word, then a pop-up dialog appears with 3 quick fixes. Select “Import ‘Ignore’ (org.junit)”. This add the import at the top of the soruce file, and the red squiggly line disappears.

Add the @Ignore annotation for each of the other methods except the “testAdd()” method. Now right-click on the file “” and select “Run As > JUnit Test”. Below is the screenshot.

JUnit testAdd Ignore

Notice the solid green bar on the top right? That means all the tests passed. If you look at the Runs, 6 tests were ignored. Also you can tell they are ignored for example by looking at “testRemove”, it’s got a greyed out line through it, as do the other tests. Except “testAdd”, which is green so it passed.

So how do we fix the circular dependencies in the file? The simple answer is, for the example class I’ve given, we’ll need to create a single test that will create the array and perform JUnit tests on each of the methods of the class. So get rid of the methods “testAdd()”, “testRemove()”, etc… until we only have “testIntArray()” method left.

Finally I’ve modified the “testIntArray()” method so that it verifies each of the methods of the “” class file that we originally created. Below is a screenshot of the code that was created.

JUnit testIntArray

Now if you run this in Eclipse, notice the last test “assertEquals(3,testArray.size());” fails. This is because we removed all elements from the array so it is empty, and size will return “-1”. Change that line to “assertEquals(-1,testArray.size());” then run in Eclipse as a JUnit Test.

Everything is green. The tests pass! Notice that I’m testing all methods of the class.

I’ve shown most of the basic use and functionality of JUnit. You should be able to write your own test cases in Eclipse now.

I’ve placed this Eclipse project on Github in case y0u need the source code as a reference.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: