VOOZH about

URL: https://www.javacodegeeks.com/understanding-beforetest-and-beforemethod-in-testng.html

⇱ Understanding @BeforeTest and @BeforeMethod in TestNG - Java Code Geeks


In TestNG, annotations like @BeforeTest and @BeforeMethod play a crucial role in setting up the test environment. While they might seem similar, they serve different purposes and are executed at different stages during the test lifecycle. Understanding their behaviour is essential to designing an effective test structure. This article explores the differences between @BeforeTest and @BeforeMethod with code examples.

1. What is @BeforeTest?

The @BeforeTest annotation is used to execute a method once, prior to any test methods annotated with @Test in a test class, making it ideal for setting up shared resources or configurations required for the tests. It is basically used to set up resources shared across multiple test methods within the same test class.

To use TestNG in a Java project, we need to add the TestNG dependency to our pom.xml file. Below is the Maven configuration:

<dependency>
 <groupId>org.testng</groupId>
 <artifactId>testng</artifactId>
 <version>7.10.2</version>
 <scope>test</scope>
</dependency>

Below is an example demonstrating the usage of the @BeforeTest annotation.

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class BeforeTestExample {

 @BeforeTest
 public void setUpTestEnvironment() {
 System.out.println("Setting up test environment...");
 }

 @Test
 public void testOne() {
 System.out.println("Executing Test One");
 }

 @Test
 public void testTwo() {
 System.out.println("Executing Test Two");
 }
}

In the above code, The setUpTestEnvironment method, annotated with @BeforeTest, ensures it runs once before any test methods like testOne and testTwo. The output when the above code is executed:

Setting up test environment...
Executing Test One
Executing Test Two

Note: Use @BeforeTest when you need to perform one-time setup tasks like initializing a database, starting a server, or setting up global configurations.

2. What is @BeforeMethod?

The @BeforeMethod annotation is executed before each test method in a current test class. It is useful for tasks that must be repeated for each test method, such as resetting variables, preparing test data, or setting up the state for individual tests. Here is an example demonstrating the usage of the @BeforeMethod annotation.

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class BeforeMethodExample {

 @BeforeMethod
 public void setUpBeforeEachMethod() {
 System.out.println("Setting up before each test method...");
 }

 @Test
 public void testA() {
 System.out.println("Executing Test A");
 }

 @Test
 public void testB() {
 System.out.println("Executing Test B");
 }
}

In this example, the setUpBeforeEachMethod method is annotated with @BeforeMethod, ensuring it runs before each test method (testA and testB). The output when the above code is executed:

Setting up before each test method...
Executing Test A
Setting up before each test method...
Executing Test B

Note: Use @BeforeMethod when you need to prepare a fresh state for each test to ensure isolation and avoid inter-test dependencies.

3. Key Differences Between BeforeTest and BeforeMethod

Aspect@BeforeTest@BeforeMethod
Execution Frequencyensures it runs once before any test methodsRuns before each test method in the class
Use CaseOne-time setup for multiple test methodsPer-method setup for isolated testing
ScopeApplies to all methods in the @test annotationApplies to individual test methods
Common TasksInitializing global resourcesResetting variables or state

4. Combining BeforeTest and BeforeMethod

Sometimes, you might need both @BeforeTest and @BeforeMethod in the same class to handle one-time setup and per-method setup.

import org.testng.annotations.BeforeTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class CombinedExample {

 @BeforeTest
 public void setUpTestEnvironment() {
 System.out.println("Setting up test environment (once)...");
 }

 @BeforeMethod
 public void setUpBeforeEachMethod() {
 System.out.println("Setting up before each test method...");
 }

 @Test
 public void testOne() {
 System.out.println("Executing Test One");
 }

 @Test
 public void testTwo() {
 System.out.println("Executing Test Two");
 }
}

In the above example, the setUpTestEnvironment method runs once before any test methods in the @test annotation, while the setUpBeforeEachMethod method is executed before each test method, ensuring a fresh state for every test. The following screenshot shows the output when the above code is executed:

4.1 When to Use BeforeTest or BeforeMethod

  • Use @BeforeTest when you need to set up shared resources for a group of tests.
  • Use @BeforeMethod when you need to prepare a clean state for each test method.
  • Combine both when there are distinct one-time setup tasks and per-method setup requirements.

5. Conclusion

In this article, we explored the key differences between the @BeforeTest and @BeforeMethod annotations in TestNG. We demonstrated how @BeforeTest executes once before any test methods in the test class, making it suitable for one-time setup tasks, while @BeforeMethod is run before each individual test method, ensuring a fresh state for every test. By understanding when and how to use these annotations, you can better structure your TestNG tests, improving efficiency and maintainability.

6. Download the Source Code

This article explored the differences between Java TestNG BeforeTest vs BeforeMethod.

Download
You can download the full source code of this example here: java testng beforetest vs beforemethod
Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

👁 Photo of Omozegie Aziegbe
Omozegie Aziegbe
January 17th, 2025Last Updated: January 15th, 2025
0 430 3 minutes read

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz