eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Overview

When working with TestNG in Java, efficiently managing test setup and teardown is essential for creating clean, isolated, and maintainable tests. Two commonly used annotations, @BeforeTest and @BeforeMethod, serve this purpose by running setup code at different stages in the test lifecycle.

Understanding the difference between these annotations and knowing when to use each can greatly improve the organization and efficiency of our test cases.

In this tutorial, we’ll explore these annotations in detail, examine how they differ, and discuss scenarios where each is most appropriate.

2. Maven Dependency

Before diving into the annotations, let’s ensure we have TestNG added as a dependency in our Maven project’s pom.xml file :

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

3. What Is @BeforeTest?

The @BeforeTest annotation executes a method once before any test methods with @Test in our test class.

This is ideal for setting up shared resources, such as initializing an application context, manipulating an object, or setting up a database connection when multiple test methods exist within the same class.

Let’s look at an example. Before we create our test class, let’s create a class named Counter:

public class Counter {
    private int totalCount;

    public Counter(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void addCounter(int number) {
        this.totalCount = totalCount + number;
    }

    public void subtractCounter(int number) {
        this.totalCount = totalCount - number;
    }

    public void resetTotalCount() {
        this.totalCount = 0;
    }
}

Let’s create our first test class named BeforeTestAnnotationTest:

public class BeforeTestAnnotationTest {
    private static final Logger log = LoggerFactory.getLogger(BeforeTestAnnotationTest.class);

    Counter counter;

    @BeforeTest
    public void init() {
        log.info("Initializing ...");
        counter = new Counter(0);
    }

    @Test
    public void givenCounterInitialized_whenAddingValue_thenTotalCountIncreased() {
        log.info("total counter before added: {}", counter.getTotalCount());
        counter.addCounter(2);
        log.info("total counter after added: {}", counter.getTotalCount());
    }

    @Test
    public void givenCounterInitialized_whenSubtractingValue_thenTotalCountDecreased() {
        log.info("total counter before subtracted: {}", counter.getTotalCount());
        counter.subtractCounter(1);
        log.info("total counter after subtracted: {}", counter.getTotalCount());
    }
}

Now, let’s run our BeforeTestAnnotationTest:

Initializing ...
total counter before added: 0
total counter after added: 2
total counter before subtracted: 2
total counter after subtracted: 1

Here’s how the annotations and methods in the example work together:

  • When givenCounterInitialized_whenAddingValue_thenTotalCountIncreased() runs, it starts with totalCount set to 0, as initialized by @BeforeTest.
  • When givenCounterInitialized_whenSubtractingValue_thenTotalCountDecreased() runs, it uses the totalCount value left by the previous test givenCounterInitialized_whenAddingValue_thenTotalCountIncreased(), rather than resetting to 0. This explains why totalCount isn’t re-initialized for givenCounterInitialized_whenSubtractingValue_thenTotalCountDecreased() despite @BeforeTest setting it initially to 0.

4. What Is @BeforeMethod?

The @BeforeMethod annotation runs a method before each test method within a test class. It’s used for tasks that need to be reset or reinitialized before every test, such as resetting variables, clearing data, or setting up isolated conditions. This ensures that each test runs independently of others, avoiding cross-test dependencies.

In the following example, we’ll use @BeforeMethod to reset the totalCount value in our counter object before each test method.

Let’s create our second test class named BeforeMethodAnnotationTest:

public class BeforeMethodAnnotationTest {
    private static final Logger log = LoggerFactory.getLogger(BeforeMethodAnnotationTest.class);

    Counter counter;

    @BeforeTest
    public void init() {
        log.info("Initializing ...");
        counter = new Counter(0);
    }

    @BeforeMethod
    public void givenCounterInitialized_whenResetTotalCount_thenTotalCountValueReset() {
        log.info("resetting total counter value ...");
        counter.resetTotalCount();
    }

    @Test
    public void givenCounterInitialized_whenAddingValue_thenTotalCountIncreased() {
        log.info("total counter before added: {}", counter.getTotalCount());
        counter.addCounter(2);
        log.info("total counter after added: {}", counter.getTotalCount());
    }

    @Test
    public void givenCounterInitialized_whenSubtractingValue_thenTotalCountDecreased() {
        log.info("total counter before subtracted: {}", counter.getTotalCount());
        counter.subtractCounter(2);
        log.info("total counter after subtracted: {}", counter.getTotalCount());
    }
}

Now, let’s run our BeforeMethodAnnotationTest:

Initializing ...
resetting total counter value ...
total counter before added: 0
total counter after added: 2
resetting total counter value ...
total counter before subtracted: 0
total counter after subtracted: -2

Here’s how the annotations and methods in the example work together:

  • init() Method: This method is annotated with @BeforeTest, so it runs once before all unit tests, initializing totalCount to 0 for use in the counter.
  • givenCounterInitialized_whenResetTotalCount_thenTotalCountValueReset() method: With the @BeforeMethod annotation, this method runs immediately before each test. It resets totalCount to 0 before every test execution.
  • Test methods givenCounterInitialized_whenAddingValue_thenTotalCountIncreased() and givenCounterInitialized_whenSubtractingValue_thenTotalCountDecreased(): When these tests run, totalCount always starts at 0 because @BeforeMethod resets it just before each test.

5. Key Differences

Understanding the key differences between @BeforeTest and @BeforeMethod can help us decide when to use each annotation effectively. Here’s a closer look at how they differ and why both are valuable in our tests:

Aspect @BeforeTest @BeforeMethod
Execution Scope
Runs once before any test methods
Runs before each test method in the class
Use Case
Ideal for setting up configurations, initiating objects or resources shared across multiple tests
Ideal for resetting or preparing conditions for each test
Typical Usage
Environment setup, initializing objects to manipulate later, initializing resources like databases
Resetting variables, preparing test-specific configurations

6. When to Use Each Annotation

Here’s how to decide between @BeforeTest and @BeforeMethod based on their use cases:

  • We use @BeforeTest when setting up configurations or shared resources across multiple tests, such as initializing an application context, initiating objects, or setting up a shared database.
  • We use @BeforeMethod when setting up isolated conditions or resetting states that need to be independent for each test, such as resetting object values, resetting a database, or setting default values for variables before each test.

7. Conclusion

In TestNG, @BeforeTest and @BeforeMethod provide powerful tools for organizing test setups in a Java test suite. By understanding their differences, we can use @BeforeTest for shared configurations that run once, and @BeforeMethod for resetting or setting conditions specific to each test method. This helps us achieve efficient and reliable tests in Java, especially in complex environments like Spring applications.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook Jackson – NPI EA – 3 (cat = Jackson)