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 – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

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

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW