JUnit Tutorial (2) – Annotations

This article contains JUnit annotations and examples for showing how to use them. Annotations enables us to use any method names without following any conventions. Actually, it has becomes a very popular way for a lot of projects, framework, etc.

You may ask questions like: How to skip a test case in Junit? How to timeout a test? etc. Annotations can make those very simple to implement, without even writing any complex code for configuration.

@Test

This marks a method to be a test method. A test class can have MULTIPLE test methods.

@Before and @After

Will execute the method before/after each test. This method can prepare/clean up the test environment (e.g. read input data, initialize the class, delete temporary data, etc). As a class can have multiple test methods, @Before and @After methods will be executed before and after each test. This is different with @BeforeClass and @AfterClass.

@Before
public void setUp() throws Exception {
    //setup something
}
 
@After
public void tearDown() throws Exception {
    //tear down something
}

@BeforeClass and @AfterClass

@BeforeClass executes before the start of tests. This can be used to perform time intensive activities, e.g., connect to a database. @AfterClass executes after all tests have finished. This can be used to perform clean-up activities, e.g., disconnect from a database. Those two only run one time no matter how many test the class has. Also you have to declare “@BeforeClass” and “@AfterClass” method as static method. The two annotations should be used do some static initialization code and destroy static variables.

@BeforeClass
public static void runBeforeClass() {
// run before all test cases
}
 
@AfterClass
public static void runAfterClass() {
// run after all test cases
}

@Ignore

Will ignore 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.

@Ignore("ignored method")  
@Test
public void someTestMethod() {  
	  System.out.println("Method is ignored");
}

@Test (expected = Exception.class)

If a test case expects some exception, use this annotation. It fails, if the method does not throw the named exception.

@Test(expected = ArithmeticException.class)  
public void divisionWithException() {  
	int i = 1/0;
}

@Test(timeout=100)

If you want to time out a test, use timeout annotation. It will fail, if the method takes longer than 100 milliseconds.

@Test(timeout = 100)  
public void timeoutMethod() {  
	while (true);  
}
Category >> Software Testing