Home > Java, JUnit > Unit testing with JUnit

Unit testing with JUnit


unit test is a piece of code written by a developer that executes a specific functionality in the code which is tested. The percentage of code which is tested by unit tests is typically called test coverage.

Unit tests target small units of code, e.g. a method or a class, (local tests) whereas component and integration tests targeting to test the behavior of a component or the integration between a set of components or a complete application consisting of several components.

Unit tests ensure that code works as intended. They are also very helpful to ensure that the code still works as intended in case you need to modify code for fixing a bug or extending functionality. Having a high test coverage of your code allows you to continue developing features without having to perform lots of manual tests.

Typically unit tests are created in their own project or their own source folder to avoid that the normal code and the test code is mixed.

To integrate the unit testing to your application you need to use unit testing library. Here are couple of annotations used in the unit testing.

Annotation Description
public void method()
The annotation @Test identifies that a method is a test method.
public void method()
This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
public void method()
This method is executed after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
public static void method()
This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
public static void method()
This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@Ignore Ignores the test method. This is useful when the underlying code has been changed and the test case has not yet been adapted. Or if the execution time of this test is too long to be included.
@Test (expected = Exception.class) Fails, if the method does not throw the named exception.
@Test(timeout=100) Fails, if the method takes longer than 100 milliseconds.


JUnit provides static methods in the Assert class to test for certain conditions. These assertion methods typically start with asserts and allow you to specify the error message, the expected and the actual result. An assertion method compares the actual value returned by a test to the expected value, and throws an AssertionException if the comparison test fails.

The following table gives an overview of these methods. Parameters in [] brackets are optional.

Statement Description
fail(String) Let the method fail. Might be used to check that a certain part of the code is not reached. Or to have a failing test before the test code is implemented.
assertTrue([message], boolean condition) Checks that the boolean condition is true.
assertsEquals([String message], expected, actual) Tests that two values are the same. Note: for arrays the reference is checked not the content of the arrays.
assertsEquals([String message], expected, actual, tolerance) Test that float or double values match. The tolerance is the number of decimals which must be the same.
assertNull([message], object) Checks that the object is null.
assertNotNull([message], object) Checks that the object is not null.
assertSame([String], expected, actual) Checks that both variables refer to the same object.
assertNotSame([String], expected, actual) Checks that both variables refer to different objects.

Lets create a simple java application with the Junit integration.

First create the class which should be tested.


package com.vogella.junit.first;

public class MyClass {

public int multiply(int x, int y){

 throw new IllegalArgumentException("X should be less than 1000");

 return x*y;

Then create a separate source folder to place the unit testing class to the application. This can be added by New->Junit class option in the eclipse.

package com.vogella.junit.first;

import static org.junit.Assert.*;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class MyClassTest {

 public static void testSetup() {


 public static void testCleanup() {

 public void testExceptionIsThrown(){
 MyClass tester = new MyClass();
 tester.multiply(1000, 5);

 public void testMultiply() {
 MyClass tester = new MyClass();
 assertEquals("10 x 5 must be 50", 50, tester.multiply(10, 5));


Now run the application as a junit test.


These results show that the MyClass.java functionalities are working properly.

Categories: Java, JUnit
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: