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

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.

Comments 10

  • 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();
    }

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

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

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

  • 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

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

  • 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”));
    }

  • Wonderful, thanks a lot. Really helped me.
    Thanks also to Safraz for giving the Selenium2 variant.
    Because of a question for a realtime application, I thought of pasting my code. No problem with company code, since I am still learning and using Mercury Tours site.
    I have only 1 @Test annotation, but I use parameters in a csv file and Page Objects. Everything run nice, the test opened the browser only once. My test returns to the Home page after the run so that the other iteration’s user can log on. The test, though, does not log another user immediately, first it reopens the Home page url, as it did in the beginning, but that’s a minor problem.
    Please don’t critisize my code :). Hope it will help someone.

    package tests;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;

    import org.junit.After;
    import org.junit.AfterClass;
    import org.junit.Before;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import org.junit.runners.Parameterized.Parameters;

    import pages.BookFlightPage;
    import pages.Browser;
    import pages.FlightConfirmationPage;
    import pages.HomePage;
    import pages.ReservationPage;
    import pages.ReservationResults;
    import pages.SignOnPage;

    @RunWith(value = Parameterized.class)
    public class TestDataDrivenBrowsing1 {
    // members:
    //I use a Browser class, I don’t initialize WebDriver here
    public static Browser browser;
    //the csv file path is linux, that’s what I use at home.
    private static String filePath = “/home/mike/workspace/newtours/src/main/resources/testdata.csv”;
    private String firstName;
    private String lastName;
    private String loginName;
    private String password;

    // @Before
    // public void setUp() throws Exception {
    // browser = new Browser();
    // }

    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    browser = new Browser();
    }

    // @After
    // public void tearDown() throws Exception {
    // browser.close();
    // }

    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    browser.close();
    }

    @Parameters
    public static Collection testData() throws IOException {
    return getTestData(filePath);
    }

    public TestDataDrivenBrowsing1(String firstName, String lastName,
    String loginName, String password) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.loginName = loginName;
    this.password = password;
    }

    public static Collection getTestData(String fileName)
    throws IOException {
    List records = new ArrayList();
    String record;
    BufferedReader file = new BufferedReader(new FileReader(fileName));
    while ((record = file.readLine()) != null) {
    String fields[] = record.split(“,”);
    records.add(fields);
    }
    file.close();
    return records;
    }

    @Test
    public void testFacebookRegistration() throws Exception {
    //this is just to see that it can print it out to console
    System.out.println(“Iteration”);
    System.out.println(“–“);
    System.out.println(firstName);
    System.out.println(lastName);
    System.out.println(loginName);
    System.out.println(password);

    HomePage homepage = new HomePage(browser.driver());
    homepage.load();
    homepage.get(); //I use get() to call overloaded functions in LoadableComponent
    ReservationPage reservationpage = homepage.login(loginName,password);
    reservationpage.get();
    ReservationResults resresults = reservationpage.selectFlight();
    resresults.get();
    BookFlightPage bookflight = resresults.getFlight();
    bookflight.get();
    FlightConfirmationPage flightconfirm = bookflight.bookFlight(firstName,lastName);
    flightconfirm.get();
    SignOnPage signon = flightconfirm.signOff();
    signon.get();
    homepage = signon.backToHome();
    homepage.get();
    }
    }

  • Hi all ,

    java.lang.NullPointerException
    at com.qmic.masarak.selenium.webdriver.pages.HomePage.logOut(HomePage.java:206)
    at com.qmic.masarak.selenium.webdriver.pages.HomePage.verifyMasarakLoginNoDataEnteredErrorMessages(HomePage.java:806)
    at com.qmic.masarak.selenium.test.application.TestHomePage.testVerifyMasarkLoginFunctionalityAndAllIncorrectCreditionalsErrorMessage(TestHomePage.java:25)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at junit.framework.TestCase.runTest(TestCase.java:168)
    at junit.framework.TestCase.runBare(TestCase.java:134)
    at junit.framework.TestResult$1.protect(TestResult.java:110)
    at junit.framework.TestResult.runProtected(TestResult.java:128)
    at junit.framework.TestResult.run(TestResult.java:113)
    at junit.framework.TestCase.run(TestCase.java:124)
    at junit.framework.TestSuite.runTest(TestSuite.java:243)
    at junit.framework.TestSuite.run(TestSuite.java:238)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

    I am getting above exception while running selenium tests.

    Main class I am mentioned firefox setup.
    Please find below code.
    public class ab extends TestCase{
    private static StringBuffer verificationErrors = new StringBuffer();
    private String className , testMethodName ;
    public WebDriver driver ;
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
    MasarakWebportalTestCase mwt = new MasarakWebportalTestCase();
    FirefoxProfile firefoxProfile = new FirefoxProfile();
    DesiredCapabilities cap = DesiredCapabilities.firefox();
    firefoxProfile.setEnableNativeEvents(false);
    cap.setCapability(“firefox_profile”, firefoxProfile);
    mwt.launch(firefoxProfile);
    RemoteControlConfiguration rc = new RemoteControlConfiguration();
    rc.setTrustAllSSLCertificates(true);
    mwt.maximize();
    }

    public void launch (FirefoxProfile firefoxProfile) throws Exception {
    driver = new FirefoxDriver(firefoxProfile);
    driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
    driver.get(Utility.baseUrl);
    }

    @Rule
    public TestName testName = new TestName();

    @Before
    public void setUpBeforeTest () throws Exception {
    className = this.getClass().getSimpleName();
    testMethodName = testName.getMethodName();
    System.out.println(className + ” ” +testMethodName +” starts run”);
    DriverFunction driverFunction = new DriverFunction (driver);
    driverFunction.verifyLogin();
    driverFunction.gotoProperAssignedLoacation(className);
    }

    public void maximize() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension screenResolution = new Dimension((int) toolkit.getScreenSize().getWidth(), (int)
    toolkit.getScreenSize().getHeight());
    driver.manage().window().setSize(screenResolution);
    }

    @After
    public void tearDown() throws Exception {
    try {
    className = this.getClass().getSimpleName();
    testMethodName = testName.getMethodName();
    System.out.println(testMethodName +” Finished”);
    String fileName = className+”(“+testMethodName.trim()+”)”+GlobalConstants.loadRoleName;
    takeScreenShotMethod(fileName);
    } catch (Exception e ) {
    System.out.println(e+””);
    }
    String verificationErrorString = verificationErrors.toString();
    if (!””.equals(verificationErrorString)) {
    fail(verificationErrorString);
    }
    }
    public void terminate () throws Exception {
    driver.close();
    driver.quit();
    }
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
    MasarakWebportalTestCase mwt = new MasarakWebportalTestCase();
    mwt.terminate();
    }
    }

  • Heck yeah this is exlatcy what I needed.

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.