Konstantina Dimtsa

About Konstantina Dimtsa

Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

JUnit Getting Started Example

In this example we are going to introduce some basic annotations and asserts of JUnit4. JUnit4 is a test framework which is used by developers so that they can be ensured that their code works as expected.

1. Create Junit Test

Open Eclipse IDE and create a new Java project called JunitFirstTest.
It would be better to create a new source folder to place your test classes and not combine them with the java classes in the src folder. For that purpose, right click on the project and select New → Source Folder so as to create test folder.
 

02-Nov-13 5-39-37 PM

In the screenshot above we can see the structure of the project after the creation of the new source folder.

In the test folder, first create a new package com.javacodegeeks.junit and then create a Junit Test by right-clicking on the previous package and selecting New → Junit Test Case.

02-Nov-13 5-03-59 PM22

If your project does not contain the JUnit library in its classpath, the following message will be displayed so as to add the JUnit library to the classpath.

02-Nov-13 5-49-38 PM22

Now create a test with the code below.

JunitFirstTest.java:

package com.javacodegeeks.junit;

import static org.junit.Assert.*;
import java.util.*;
import org.junit.*;

public class JunitFirstTest {

    private ArrayList<String> testList;

    @BeforeClass
    public static void onceExecutedBeforeAll() { 
    	System.out.println("@BeforeClass: onceExecutedBeforeAll");
    }

    @Before
    public void executedBeforeEach() {
        testList = new ArrayList<String>();
        System.out.println("@Before: executedBeforeEach");
    }

    @AfterClass
    public static void onceExecutedAfterAll() {
    	System.out.println("@AfterClass: onceExecutedAfterAll");
    }

    @After
    public void executedAfterEach() {
        testList.clear();
        System.out.println("@After: executedAfterEach");
    }

    @Test
    public void EmptyCollection() {
        assertTrue(testList.isEmpty());
        System.out.println("@Test: EmptyArrayList");

    }

    @Test
    public void OneItemCollection() {
        testList.add("oneItem");
        assertEquals(1, testList.size());
        System.out.println("@Test: OneItemArrayList");
    }
}

Let’s describe the annotations in the above code in detail.

@Test
public void method()
The Test annotation indicates that the public void method to which it is attached can be run as a test case.
@Before
public void method()
The Before annotation indicates that this method must be executed before each test in the class, so as to execute some preconditions necessary for the test.
@BeforeClass
public static void method()
The BeforeClass annotation indicates that the static method to which is attached must be executed once and before all tests in the class. That happens when the test methods share computationally expensive setup (e.g. connect to database).
@After
public void method()
The After annotation indicates that this method gets executed after execution of each test (e.g. reset some variables after execution of every test, delete temporary variables etc)
@AfterClass
public static void method()
The AfterClass annotation can be used when a method needs to be executed after executing all the tests in a JUnit Test Case class so as to clean-up the expensive set-up (e.g disconnect from a database). Attention: The method attached with this annotation (similar to BeforeClass) must be defined as static.

Also, in the code we can see two assert statements. Here is a short explanation of them.

assertTrue (String message, boolean condition)Asserts that the condition is true.
assertEquals ([String message], object expected, object actual)Asserts that the two objects are equal.

2. Run your test in Eclipse

Now, run your test in Eclipse, so as to see the results. Right-click on your JunitFirstTest class and select Run As→JUnit Test.

Outputs:

@BeforeClass: onceExecutedBeforeAll
@Before: executedBeforeEach
@Test: EmptyArrayList
@After: executedAfterEach
@Before: executedBeforeEach
@Test: OneItemArrayList
@After: executedAfterEach
@AfterClass: onceExecutedAfterAll

As we see in the results, the sequence of the executed methods complies with what we described in the previous section.

Download the Eclipse Project

This was an introduction to JUnit basic annotations and assert statements. Download the Eclipse Project of this example : JunitFirstTest.zip

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.