JUnit 4 – Introduction to “Annotations”

JUnit 4 introduced a new feature called “annotations”.  This helps greatly in automating test cases.  I agree that knowledge of Java programming language can help in implementing a robust test automation framework.  But the testers who don’t have knowledge of Java will be really benefited by “annotations”

We will try to understand this feature in detail with the below code snippet:

package com.example.tests;

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;

public class JUnitTest extends SeleneseTestCase {
	@Before
	public void setUp() throws Exception {
		selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.co.in/");
		selenium.start();
	}

	@Test
	public void testSearchBlog() throws Exception {
		selenium.open("htt://www.google.com");
		selenium.type("q", "selftechy");
		selenium.click("//ol[@id='rso']/li[1]/div/span/h3/a[1]/em");
		selenium.waitForPageToLoad("30000");
	}

	@After
	public void tearDown() throws Exception {
		selenium.stop();
	}
}

In the above code we can see something like “@Test, @After, @Before”, these are known as “Annotations”

When it is mentioned as @Test before a test method, it tells JUnit framework that the following is a Test Method.

The same way if the annotation is @Before that says “execute the method before executing the Test Method”

If the annotation is @After then that method will be executed after the execution of the Test Method

Hence, After and Before annotations are used to setup & teardown the environment.  In the next post we will learn what is the drawback of @Before and @After, if there are multiple test cases in a class

Comments 2

  • Hi,

    Can new annotations be added to junit? If yes, could you please tell me how to add annotations manually.

    Thanks,
    Sneha

  • Yes, we can create annotations.

    In eclipse, open a new file for annotation and write the appropriate code. Then make a jar file from this annotations java file. Use the annotations Jar file in the project by adding the jar file to build path.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.