Junit Tutorial â€“ Basic Usage and Annotation

This tutorial introduces how to write testcase with Junit 4Â and explains basic annotations supported in junit 4.

TableÂ 1.Â Annotations

Annotation

Description

@Test public void method()

The annotation @Test identifies that a method is a test method.

@Before public void method()

Will execute the method before each test. This method can prepare the test environment (e.g. read input data, initialize the class).

@After public void method()

Will execute the method after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults).

@BeforeClass public void method()

Will execute the method 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 a static modifier to work with JUnit.

@AfterClass public void method()

Will execute the method once, after all tests have finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with @AfterClass need a static modifier to work with JUnit.

@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.

MethodsÂ annotatedÂ withÂ @BeforeClass and @AfterClassÂ were onlyÂ executed once, before the start of all tests or after the end of all tests,Â they are twoÂ new annotations introduced in junit 4. the disadvantage is thatÂ methods annotated with @beforeClass and @AfterClassÂ need a static modifier.