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
@Test
public void method()
The annotation @Test identifies that a method is a test method.
@BeforeClass
public static void oneTimeSetUpMethod()
This method is executed before the first test method
@AfterClass
public static void oneTiemtearDownMethod()
This method is executed after the last test method
@Before
public void setUp()
This method is executed before each test
@After
public void tearDown()
This method is executed after each test
@Ignore
@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.
@Test(timeout=100)
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

  <dependencies>
   	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.10</version>
	</dependency>
  </dependencies>

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 {
	@BeforeClass
    public static void oneTimeSetUpMethod() {
		 // Code executed before the first test method  
    	System.out.println("@BeforeClass called");
    }
	
	@AfterClass
    public static void oneTiemtearDownMethod() {
		// Code executed after the last test method
    	System.out.println("@AfterClass called");
    }
 
	@Before
    public void setUp() {
		// Code executed before each test    
        System.out.println("@Before called");
    }
	
	@After
    public void tearDown() {
		// Code executed after each test     
        System.out.println("@After called");
    }
	 
	@Test
	public void testAdd(){
		assertEquals(15, 10 + 5);
		System.out.println("@Test called - Addition");
	}
	
	@Test
	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