JUnit4 – @Before vs @BeforeClass / @After vs @AfterClass

by seetaram on May 17, 2011

In JUnit4 @Before is used to execute set of preconditions before executing a test.  For example, if there is a need to open some application and create a user before executing a test, then this annotation can be used for that method.  Method that is marked with @Before will be executed before executing every test in the class.

Method that is marked with @After gets executed after execution of every test.  If we need to reset some variable after execution of every test then this annotation can be used with a method that has the needed code.

If a JUnit test case class contains lot of tests which all together need a method which sets up a precondition and that needs to be executed before executing the Test Case class then we can utilize “@BeforeClass” annotation.

In the same way “@AfterClass” annotation can be used to execute a method that needs to be executed after executing all the tests in a JUnit Test Case class.

To demonstrate these annotations we will try to create “three tests” in two different JUnit test case classes – First & Second

  1. Create a project in Eclipse (e.g. SampleProject)
  2. Create a package under Project (Right Click SampleProject –> com.selftechy.junit4)
  3. Create JUnit Test Case (Select JUnit4) – give name (e.g. FirstTC)
  4. Now using Selenium IDE record below three different tests

Test – 1:

  1. Open Google
  2. Click on Advanced Search
  3. Type in some Search Keywords
  4. Select “20 Results per”
  5. Click on Advanced Search

Test – 2:

  1. Open Google
  2. Click on Language Tools
  3. Type in “Google is an excellent Search Engine” in Translate Text
  4. Select English >> Spanish
  5. Click on Translate
  6. Verify translated Sentence “Google es un excelente motor de búsqueda”

Test – 3:

  1. Open Google
  2. Click on Advertising Programs
  3. Click on “Learn more”
  4. Verify “Google Adsense” Logo
  5. Verify Sign-in page

First we will try writing tests with @Before & @After:

Code should be as below :

package com.selftechy.junit4;

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

	@Test
	public void testAdvancedSearch() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Advanced search");
		selenium.waitForPageToLoad("30000");
		selenium.type("as_q", "Selenium, selftechy, eclipse");
		selenium.select("num", "label=20 results");
		selenium.click("//input[@value='Advanced Search']");
		selenium.waitForPageToLoad("30000");
	}

	@Test
	public void testLanguageTools() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Language tools");
		selenium.waitForPageToLoad("30000");
		selenium.type("source", "Google is an excellent Search Engine");
		selenium.select("sl", "label=English");
		selenium.select("tl", "label=Spanish");
		selenium.click("//input[@value='Translate']");
		selenium.waitForPageToLoad("30000");
		verifyTrue(selenium.isElementPresent("//span[@id='result_box']/span"));
	}

	@Test
	public void testAdvertisingPrograms() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Advertising Programs");
		selenium.waitForPageToLoad("30000");
		selenium.click("link=Learn more");
		selenium.waitForPageToLoad("30000");
		verifyTrue(selenium.isElementPresent("//img[@alt='Google AdSense']"));
		verifyTrue(selenium.isElementPresent("Email"));
		verifyTrue(selenium.isElementPresent("Passwd"));
		assertTrue(selenium.isElementPresent("signIn"));
		verifyTrue(selenium.isElementPresent("signIn"));
	}

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

Copy the same code into the created JUnit Test Class and then execute as a JUnit Test.

You should be able to observe that for each test Browser will be opened, runs the test, then kills the browser.  This is because for each test, SetUp and tearDown methods are getting executed.

Let me demonstrate the usage of @BeforeClass & @AfterClass in the following test case:

package com.selftechy.junit4;

import com.thoughtworks.selenium.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class Second extends SeleneseTestCase {

	@BeforeClass
	public void setUpBeforeClass() throws Exception {
		selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.co.in/");
		selenium.start();
	}

	@Test
	public void testAdvancedSearch() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Advanced search");
		selenium.waitForPageToLoad("30000");
		selenium.type("as_q", "Selenium, selftechy, eclipse");
		selenium.select("num", "label=20 results");
		selenium.click("//input[@value='Advanced Search']");
		selenium.waitForPageToLoad("30000");
	}

	@Test
	public void testLanguageTools() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Language tools");
		selenium.waitForPageToLoad("30000");
		selenium.type("source", "Google is an excellent Search Engine");
		selenium.select("sl", "label=English");
		selenium.select("tl", "label=Spanish");
		selenium.click("//input[@value='Translate']");
		selenium.waitForPageToLoad("30000");
		verifyTrue(selenium.isElementPresent("//span[@id='result_box']/span"));
	}

	@Test
	public void testAdvertisingPrograms() throws Exception {
		selenium.open("http://www.google.co.in/");
		selenium.click("link=Advertising Programs");
		selenium.waitForPageToLoad("30000");
		selenium.click("link=Learn more");
		selenium.waitForPageToLoad("30000");
		verifyTrue(selenium.isElementPresent("//img[@alt='Google AdSense']"));
		verifyTrue(selenium.isElementPresent("Email"));
		verifyTrue(selenium.isElementPresent("Passwd"));
		assertTrue(selenium.isElementPresent("signIn"));
		verifyTrue(selenium.isElementPresent("signIn"));
	}

	@AfterClass
	public void tearDownAfterClass() throws Exception {
		selenium.stop();
	}

}

Copy the above code into Second JUnit test case and execute as JUnit Test.  Observe the execution, this executes in a different way than the previous one.

Because the method with @BeforeClass will be executed only once before executing all the tests and at the end of the execution @AfterClass will be executed.

I think this demonstrates the difference between both the type of annotations and also when they need to be used.

{ 7 comments… read them below or add one }

Safraz July 21, 2011 at 5:36 am

Thanks a lot for this post..

Here is how you do it in Selenium 2:

public class Second {
public static WebDriver driver;
public static String baseUrl=”http://www.google.com/”;

@BeforeClass
public static void setUpBeforeClass() throws Exception {

driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(baseUrl);
}

@Test
xxxxxxxxxx

@Test
xxxxxxxxxx

@Test
xxxxxxxxxx

@AfterClass
public static void tearDownAfterClass() throws Exception {
driver.quit();
}

Reply

seetaram July 21, 2011 at 9:21 am

In Selenium 2.0, APIs are different. For example instead of directly using Selenium.click we use “driver.findElement(By.xpath(“xpath”)).click()”. In this statement By.xpath is explicitly specified. i.e. By.id, By.name, etc. But in Selenium 1.x we needed to pass only the locator which might be one of the ID, name, css, xpath, etc.

Reply

Murali Kedari September 26, 2012 at 10:38 am

So nice, If u provide actual Scripts code for real time applications, It would be better.

Reply

seetaram October 2, 2012 at 6:33 pm

Hi Murali,

I cannot share any of the code from my project because that will violate the company rules and regulations and also the code is their property how I can share that?. This blog is created out of my interest and not at all related to the company where I am working.

Reply

Rahul Singh October 2, 2012 at 5:18 am

HI seetaram,

Thanks for the nice post but there is a problem with me that when I copy paste this code in my eclipse and execute it, it does not executes the before class method and executes all the tests explicitly in IE even I have given the code to execute it in firefox.
Please tell me if I have a wrong version of junit or any other mistake I am doing.

Regards,
Rahul Singh

Reply

Abhishek October 19, 2012 at 11:42 am

Excellent….Thanks for clearly mentioning the difference between @Before and @BeforeClass…..

Reply

Sreedhar June 21, 2013 at 11:29 am

Hi,
I need Help.
I writing code in java.
In TestNG please give sampe code for assertTrue statement.
Please find the below code.
@Test(description=”Enters valid login data”)
public void loginAsAdmin() {
selenium.type(“user_login”, “admin”);
selenium.type(“user_pass”, “demo123″);
selenium.click(“wp-submit”);
selenium.waitForPageToLoad(“30000″);
assertTrue(selenium.isTextPresent(“Howdy, admin”));
}

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