JUnit 4 – Introduction to “Annotations”

by seetaram on May 15, 2011

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

{ 2 comments… read them below or add one }

Sneha November 28, 2011 at 7:33 am

Hi,

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

Thanks,
Sneha

Reply

seetaram November 28, 2011 at 12:30 pm

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.

Reply

Leave a Comment

Previous post:

Next post:

Do you want to get updates on the recent articles written? Please subscribe to RSS feed or Email