JUnit Testing using Annotation

A JUnit test fixture is a Java object. With older versions of JUnit, fixtures had to inherit from junit.framework.TestCase. Now with JUnit 4 Test methods must be annotated by the @Test annotation.

Table 1.1 Annotations in JUnit 4.x.
Annotation Description
public void method()
The annotation @Test identifies that a method is a test method.
public static void oneTimeSetUpMethod()
This method is executed before the first test method
public static void oneTiemtearDownMethod()
This method is executed after the last test method
public void setUp()
This method is executed before each test
public void tearDown()
This method is executed after each test
public void method()
This annotation will ignore the test method.
@Test (expected = Exception.class)
public void method()
Test Method fails, if the method does not throw the named exception.
public void method()
Test Method fails, if the method takes longer than specified milliseconds.

Note – You have to declare “@BeforeClass” and “@AfterClass” method as static method.

Following example demonstrates the basic annotations supported in JUnit 4.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml


1. JUnit Class

Create following class

package com.kruders.junit;

import static org.junit.Assert.assertEquals;

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

public class JUnitTesting {
    public static void oneTimeSetUpMethod() {
		 // Code executed before the first test method  
    	System.out.println("@BeforeClass called");
    public static void oneTiemtearDownMethod() {
		// Code executed after the last test method
    	System.out.println("@AfterClass called");
    public void setUp() {
		// Code executed before each test    
        System.out.println("@Before called");
    public void tearDown() {
		// Code executed after each test     
        System.out.println("@After called");
	public void testAdd(){
		assertEquals(15, 10 + 5);
		System.out.println("@Test called - Addition");
	public void testSubtract(){
		assertEquals(5, 10 - 5);
		System.out.println("@Test called - Subtraction");

2. Testing

When you run the above example you’ll get an output like:

@BeforeClass called
@Before called
@Test called – Addition
@After called
@Before called
@Test called – Subtraction
@After called
@AfterClass called

You can download the source code of this example here.

No comments yet.

Leave a Reply