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 Using Assertions and Annotations Example

In this example we are going to create test cases so as to understand the use of assertions and annotations in JUnit testing framework. Also, we will see how to run these test cases from the command line by using the org.junit.runner.JUnitCore. If you prefer running your test cases via Eclipse, you can have a look at JUnit Getting Started Example.

Assertion

Let’s start with an example with the most important assertion methods in JUnit.
 
 

1. Create a JUnit test

Create a folder named JUnitAssertions. This is the folder where your classes will be located. Using Notepad or another text editor, create a Java class named JunitAssertionsTest.java with the following code.

JunitAssertionsTest.java

import static org.junit.Assert.*;
import org.junit.Test;

public class JunitAssertionsTest {

	@Test
	public void test() {
		String obj1 = "junit";
		String obj2 = "junit";
		String obj3 = "test";
		String obj4 = "test";
		String obj5 = null;
		int var1 = 1;
		int var2 = 2;
		int[] arithmetic1 = { 1, 2, 3 };
		int[] arithmetic2 = { 1, 2, 3 };

		assertEquals(obj1, obj2);

		assertSame(obj3, obj4);

		assertNotSame(obj2, obj4);

		assertNotNull(obj1);

		assertNull(obj5);

		assertTrue(var1 < var2); 		

        assertFalse(var1 > var2);

		assertArrayEquals(arithmetic1, arithmetic2);
	}

}

In the above code we notice that there is a number of assertion methods. All those methods are provided by the Assert class which extends the class java.lang.Object and they are useful for writing tests so as to detect failures. In the table below there is a more detailed explanation of the assertion methods used.

void assertEquals([String message], expected value, actual value)Asserts that two values are equal. Values might be type of int, short, long, byte, char or java.lang.Object. The first argument is an optional String message.
void assertTrue([String message], boolean condition)Asserts that a condition is true.
void assertFalse([String message],boolean condition)Asserts that a condition is false.
void assertNotNull([String message], java.lang.Object object)Asserts that an object is not null.
void assertNull([String message], java.lang.Object object)Asserts that an object is null.
void assertSame([String message], java.lang.Object expected, java.lang.Object actual)Asserts that the two objects refer to the same object.
void assertNotSame([String message], java.lang.Object unexpected, java.lang.Object actual)Asserts that the two objects do not refer to the same object.
void assertArrayEquals([String message], expectedArray, resultArray)Asserts that the array expected and the resulted array are equal. The type of Array might be int, long, short, char, byte or java.lang.Object.

2. Run your test from the command line

You can run your JUnit test outside Eclipse, by using the org.junit.runner.JUnitCore class. This class provides the runClasses() method which allows you to execute one or several test classes. The return type of runClasses() method is an object of the type org.junit.runner.Result. This object can be used to collect information about the tests. Also, in case there is a failed test, you can use the object org.junit.runner.notification.Failure which holds description of the failed tests.

The procedure below shows how to run your test outside Eclipse.

In the directory JUnit Assertions, use Notepad or another editor and create a new Java class named JunitAssertionsRunner.java with the following code.

JunitAssertionsRunner.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class JunitAssertionsRunner {

	public static void main(String[] args) {

		Result result = JUnitCore.runClasses(JunitAssertionsTest.class);
		for (Failure fail : result.getFailures()) {
			System.out.println(fail.toString());
		}
		if (result.wasSuccessful()) {
			System.out.println("All tests finished successfully...");
		}
	}
}
  • Open command prompt and move down directories so as to find the directory where the two classes are located:
C:\Users\konstantina>cd JUnitAssertions
  • When JUnitAssertions is your current directory, compile the Test class and the Runner class.

Attention: To run your JUnit tests outside Eclipse properly you need to add the needed JUnit library jars to the classpath of your program. You can find those library jars here

C:\Users\konstantina\JUnitAssertions>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; junitAssertionsTest.java JunitAssertionsRunner.java
  • Now run the JunitAssertionsRunner
C:\Users\konstantina\JUnitAssertions>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitAssertionsRunner
  • Here is the output:
All tests finished successfully... 

The output shows that all the assertions in the JunitAssertionsTest.java where true.

Annotation

Now, we will show an example test case which includes all the annotations used by JUnit testing framework.

1. Create a JUnit test

Create a folder named JUnitAnnotations. This is the folder where your classes will be located. Using Notepad or another text editor, create a Java class named JunitAnnotationsTest.java with the following code.

JunitAnnotationsTest.java

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

public class JunitAnnotationsTest {

    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");
    }

   @Ignore
   public void executionIgnored() {

      System.out.println("@Ignore: This execution is ignored");
   }
}

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.
@Ignores
public static void method()
The Ignore annotation can be used when you want temporarily disable the execution of a specific test. Every method that is annotated with @Ignore won’t be executed.

2. Run your test from the command line

We will run the JunitAnnotationsTest.java following the procedure in the previous section.

In the directory JUnitAnnotations, use Notepad or another editor and create a new Java class named JunitAnnotationsRunner.java with the following code.

JunitAnnotationsRunner.java

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class JunitAnnotationsRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(JunitAnnotationsTest.class);
      for (Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      if (result.wasSuccessful()) {
	 System.out.println("All tests finished successfully...");
      }
   }
}
  • Open command prompt and move down directories so as to find the directory where the two classes are located.
C:\Users\konstantina>cd JUnitAnnotations
  • When JUnitAnnotations is your current directory, compile the Test class and the Runner class.
C:\Users\konstantina\JUnitAnnotations>javac -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitAnnotationsTest.java JunitAnnotationsRunner.java

As we mentioned in the previous section, you should include library jars of JUnit to your classpath.

  • Now run the JunitAssertionsRunner.
C:\Users\konstantina\JUnitAnnotations>java -classpath "C:\Users\konstantina\Downloads\junit-4.11.jar";"C:\Users\konstantina\Downloads\hamcrest-core-1.3.jar"; JunitAnnotationsRunner
  • Here is the output
@BeforeClass: onceExecutedBeforeAll
@Before: executedBeforeEach
@Test: EmptyArrayList
@After: executedAfterEach
@Before: executedBeforeEach
@Test: OneItemArrayList
@After: executedAfterEach
@AfterClass: onceExecutedAfterAll
All tests finished successfully...

As we see in the results, the sequence of execution of the methods complies with what we described in the annotations table. We also note that the method annotated with @Ignore was not executed.

Download the source code

This was an example of using annotations and assertions in JUnit testing framework from the command line.
Download the source code of this example : JUnitAssertions.zip JUnitAnnotations.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close