TestNG Showcase – Before and After

Similar to JUnit 4, TestNG is providing similar Before and After functionalities with the addition of @BeforeSuite and @AfterSuite. Also instead of @Before and @After as it is named in JUnit (before and after each unit test) it is now named @BeforeMethod and @AfterMethod providing though identical functionality.

An example:

package com.dimitrisli.testng.beforeAfter;

import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;

public class TestNGBeforeAfterTesting {

	public static void initialiseSuite(){
		System.out.println("init suite");

	public static void initialiseClass(){
		System.out.println("init class");
	public void initialiseTest(){
		System.out.println("init test");
	public void test1(){
		System.out.println("inside test1");

	public void test2(){
		System.out.println("inside test2");
	public void teardownTest(){
		System.out.println("teardown test");
	public static void teardownClass(){
		System.out.println("teardown class");
	public static void teardownSuite(){
		System.out.println("teardown suite");

that is yielding the following output:

init suite
init class
init test
inside test1
teardown test
init test
inside test2
teardown test
teardown class
PASSED: test1
PASSED: test2

    Default test
    Tests run: 2, Failures: 0, Skips: 0

teardown suite

Default suite
Total tests run: 2, Failures: 0, Skips: 0

You can find the code in this Github repository


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s