HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TestNG / TestNG before and after annotations

TestNG before and after annotations

TestNG Before and After annotations are mainly used to execute a certain set of code before and after the execution of test methods. These are used to basically set up some variables or configuration before the start of a test execution and then to cleanup any of these things after the test execution ends.

1. TestNG before and after annotations

TestNG provides five different kinds of Before and After annotation options, each of which can be used depending upon the test requirements. The following are the different before and after options provided by TestNG.

AnnotationDescription
@BeforeSuiteThe annotated method will be run before all tests in this suite have run.
@BeforeTestThe annotated method will be run before any test method belonging to the classes inside the test tag is run.
@BeforeGroupsThe list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked.
@BeforeClassThe annotated method will be run before the first test method in the current class is invoked.
@BeforeMethodThe annotated method will be run before all the test methods in the current class have been run.
@AfterSuiteThe annotated method will be run after all tests in this suite have run.
@AfterTestThe annotated method will be run after all the test methods belonging to the classes inside the test tag have run.
@AfterGroupsThe list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked.
@AfterClassThe annotated method will be run after all the test methods in the current class have been run.
@AfterMethodThe annotated method will be run after each test method.

Let’s try out an example containing all the preceding annotated methods and learn about when they are executed.

2. TestNG before and after annotations example

Create a new TestNG test having all before and after annotations. You can create this test with help of instructions given in this TestNG tutorial. Let’s see how you can select all before and after annotations.

Select all testng annotations

After clicking on OK, you will get a test with all annotations. Add some print statements in all methods so that they can be tracked in which order they executed.

package com.howtodoinjava.test;

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

public class MyFirstTest 
{
	@Test
	public void testCase() {
	}

	@BeforeSuite
	public void beforeSuite() {
		System.out.println("Before Suite method");
	}

	@AfterSuite
	public void afterSuite() {
		System.out.println("After Suite method");
	}

	@BeforeTest
	public void beforeTest() {
		System.out.println("Before Test method");
	}
	
	@AfterTest
	public void afterTest() {
		System.out.println("After Test method");
	}
	
	@BeforeClass
	public void beforeClass() {
		System.out.println("Before Class method");
	}

	@AfterClass
	public void afterClass() {
		System.out.println("After Class method");
	}

	@BeforeMethod
	public void beforeMethod() {
		System.out.println("Before Method");
	}

	@AfterMethod
	public void afterMethod() {
		System.out.println("After Method");
	}
}

Now run above testcase as TestNG test and you will get following output in console.

[TestNG] Running:
  C:\Users\somepath\testng-customsuite.xml

Before Suite method
Before Test method
Before Class method
Before Method
After Method
After Class method
After Test method
PASSED: testCase

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

After Suite method

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.XMLReporter@177b3cd: 19 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@b8deef: 53 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@10ab323: 13 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@5e176f: 11 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@d1e89e: 184 ms

Congratulations, you have successfully created a test class with all kinds of before and after annotations and executed it.

The current example only contains annotations that are present in the same class. Lets learn the execution flow when a class containing annotations is extended by another class having another set of before and after annotations.

3. Before and after annotations placed on super class

Let’s create two new classes BaseClass and ChildClass. Then add similar before/after annotations on both of them. Here main thing to notice is that ChildClass extends BaseClass. And Test is defined in ChildClass class.

3.1. Parent class

package com.howtodoinjava.test;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;

public class BaseClass {

	@BeforeMethod
	public void beforeMethod() {
		System.out.println("BaseClass's Before Test method");
	}

	@AfterMethod
	public void afterMethod() {
		System.out.println("BaseClass's After Test method");
	}

	@BeforeClass
	public void beforeClass() {
		System.out.println("BaseClass's Before Class method");
	}

	@AfterClass
	public void afterClass() {
		System.out.println("BaseClass's After Class method");
	}
}

2. Child Class

package com.howtodoinjava.test;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class ChildClass extends BaseClass {

	@BeforeMethod
	public void beforeChildMethod() {
		System.out.println("ChildClass's Before Test method");
	}

	@AfterMethod
	public void afterChildMethod() {
		System.out.println("ChildClass's After Test method");
	}

	@BeforeClass
	public void beforeChildClass() {
		System.out.println("ChildClass's Before Class method");
	}

	@AfterClass
	public void afterChildClass() {
		System.out.println("ChildClass's After Class method");
	}
	
	@Test
	public void testCase() {
		System.out.println("===== Executing actual test ======");
	}
}

Executing ChildClass test will generate below output.

[TestNG] Running:
  C:\Users\somepath\testng-customsuite.xml

BaseClass's Before Class method
ChildClass's Before Class method
BaseClass's Before Test method
ChildClass's Before Test method
===== Executing actual test ======
ChildClass's After Test method
BaseClass's After Test method
ChildClass's After Class method
BaseClass's After Class method
PASSED: testCase

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1549f94: 13 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@1bd7848: 16 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@1342ba4: 52 ms
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@176e552: 12 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@ff057f: 190 ms

As you can see, the report output of TestNG executes the parent class before annotated methods and then the child before annotated methods. After annotated methods, the child class method is executed and then the parent class.

This helps us to have a common before annotated methods across all test classes and have specific Before/After annotated methods for each test class where ever required.

Drop me a comment if you have any question for me.

Happy Learning !!

Reference:

TestNG docs

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. Chuck Song

    October 10, 2019

    Hi,
    I have two @AfterSuite annotation which it is a each baseClass and childClass.

    i want to run Child Class’s @AfterSuite first. how can i do this?

  2. Bikram Dhall

    November 23, 2016

    Hi ,
    I have a test case which is annotaed as @test and it takes data from DataProvider. But this testcase has also some case need to be tested prior to that. so it is in @BeforeTest.
    Suppose the test case in @BeforeTest needs some external data, how to provide data either DataProvider or parameter.

    in short: In TestNG
    it is Ok : @Tst(dataProvider =’dataProvidername’);
    ?how can i pass data into @BeforeTest annotation like aove @Test

    Rgds
    Bikram

    kindly help me in this issue.

    • Phanindra

      February 5, 2018

      Test which is present in @BeforeTest move it to Test .let say test1. mark the current @Test as dependsOnMethod=Test1

  3. Deepti Yadav

    June 21, 2016

    Hi,

    I have to test one module in which i am creating some test data & executing it .( in this process multiple steps are getting executed & data is entering into Database into different table)

    Now when i am running again the same test suite, it is saying that data already exist.

    So, what i got from the above article is.. by using @before & @after annotation, my above issue can get resolve ?

    • Lokesh Gupta

      June 21, 2016

      A unit testcase should (or must) leave the database state just like it was before the execution. It’s very basic rule of unit-testing. So using after annotation, you MUST rollback/delete the changes in database caused by unittest. Make it a practice.

      • Victor

        October 17, 2019

        A unit test should not talk with the database. Mock the database interaction.
        If it is an integration test then yes, use the Before and After to set up/clean up test data.

Comments are closed on this article!

Search Tutorials

TestNG Tutorial

  • TestNG – Introduction
  • TestNG – Hello World
  • TestNG – Maven
  • TestNG – Annotations
  • TestNG – Expected Exception
  • TestNG – Disable/Ignore Tests
  • TestNG – Parallel Tests
  • TestNG – Dependent Tests
  • TestNG – Timeout Tests
  • TestNG – @Parameters
  • TestNG – @DataProvider
  • TestNG – @Factory
  • TestNG – @DataProvider
  • TestNG – Before and After
  • TestNG – Test Groups

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces