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

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

Partner – Diagrid – NPI (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

1. Overview

In large TestNG-based suites, we often encounter scenarios where most tests pass, but a small subset fails. Re-running the entire suite in such cases is a waste of time and resources. TestNG provides several mechanisms to execute only failed tests. 

In this tutorial, we’ll explore various approaches to re-run only failed TestNG test methods, along with their examples and use cases.

2. Running the testng-failed.xml

TestNG automatically generates the testng-failed.xml file as a recovery suite after each test execution. We get this file only when our execution completes normally, at least one test fails or is skipped, and default reporters are enabled. This file captures only failed and skipped test methods while preserving our original suite structure. This allows us to re-run failures without modifying the original testng.xml.

Let’s look at the code below, which contains two test cases – one always fails:

public class ExecuteSelectivelyUnitTest {
    @Test
    public void givenTest_whenFails_thenExecuteSelectively() {
        Assert.assertEquals(5, 6);
    }

    @Test
    public void givenTest_whenPass_thenExecuteSelectively() {
        Assert.assertEquals(5, 5);
    }
}

Now, we’ll run tests using the command:

mvn test -Dtest=ExecuteSelectivelyUnitTest

We’re running our tests through Maven Surefire, and we can locate the file at target/surefire-reports/testng-failed.xml. Let’s take a look at the content of this file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Failed suite [Surefire suite]" verbose="0">
  <test thread-count="5" name="Surefire test(failed)" verbose="0">
    <classes>
      <class name="com.baeldung.testng.ExecuteSelectivelyUnitTest">
        <methods>
          <include name="givenTest_whenFails_thenExecuteSelectively"/>
        </methods>
      </class> <!-- com.baeldung.testng.ExecuteSelectivelyUnitTest -->
    </classes>
  </test> <!-- Surefire test(failed) -->
</suite> <!-- Failed suite [Surefire suite] -->

The file explicitly includes only the failed method givenTest_whenFails_thenExecuteSelectively from ExecuteSelectivelyUnitTest, excluding all passed tests. Now, we can directly run the failed test case by running the following command:

mvn test -Dsurefire.suiteXmlFiles=target/surefire-reports/testng-failed.xml

Once we trigger the above command, we can see Maven re-run only the tests listed in testng-failed.xml that were previously failed.

3. Using <include> in testng.xml

Another way to run selective tests is to create a testng.xml file manually that includes only the tests that we want to run. TestNG doesn’t require any special metadata; the file structure is similar to what we’ve seen earlier. We can add test names with selective <include> entries in the <methods> section:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Failed suite [Failed suite [Surefire suite]]" guice-stage="DEVELOPMENT" verbose="0">
  <test thread-count="5" name="Surefire test(failed)(failed)" verbose="0">
    <classes>
      <class name="com.baeldung.testng.ExecuteSelectivelyUnitTest">
        <methods>
          <include name="givenTest_whenFails_thenExecuteSelectively"/>
          <include name="method-name-here"/>
        </methods>
      </class> 
    </classes>
  </test> 
</suite>

Now, we can directly run the tests specified in testng.xml by running the following command:

mvn test -Dsurefire.suiteXmlFiles=testng.xml

This approach works well for small or ad hoc runs, giving us fine-grained control over which tests to execute. However, it requires manual editing and can become harder to maintain as the test suite grows.

4. Using Maven Surefire Single Method Execution

We can ask the Maven Surefire plugin to execute a single test method by passing -Dtest=”TestClassName#TestMethodName” to the mvn command. 

Now, let’s execute the givenTest_whenFails_thenExecuteSelectively() method in the ExecuteSelectivelyUnitTest class:

$ mvn test -Dtest=ExecuteSelectivelyUnitTest#givenTest_whenFails_thenExecuteSelectively    
...
[INFO] Scanning for projects...
...
[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.baeldung.testng.ExecuteSelectivelyUnitTest
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.379 s <<< FAILURE! -- in com.baeldung.testng.ExecuteSelectivelyUnitTest
[ERROR] com.baeldung.testng.ExecuteSelectivelyUnitTest.givenTest_whenFails_thenExecuteSelectively -- Time elapsed: 0.006 s <<< FAILURE!
java.lang.AssertionError: expected [6] but found [5]
...
[INFO] Results:
[INFO] 
[ERROR] Failures: 
[ERROR]   ExecuteSelectivelyUnitTest.givenTest_whenFails_thenExecuteSelectively:9 expected [6] but found [5]
[INFO] 
[ERROR] Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] 
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

As we can see, this time, we’ve executed only the specified test method.

5. Selective Execution via @BeforeMethod

TestNG always executes configuration methods such as @BeforeMethod and @BeforeClass before running a test. When we throw SkipException from these methods, TestNG treats it as a deliberate skip. We can evaluate conditions at this point and throw a SkipException to selectively skip tests without altering the suite definition.

Let’s take a look at the code below:

private static final Set<String> SKIP_METHODS = Set.of("givenTest_whenFails_thenExecuteSelectively");

@BeforeMethod
public void skipSelectedMethods(Method method) {
    if (SKIP_METHODS.contains(method.getName())) {
        throw new SkipException("Skipping test method: " + method.getName());
    }
}

Here, we maintained a Set of test method names to skip. Before each test run, we compare the current method name against this set and throw a SkipException when a match is found. This allows us to skip specific tests dynamically without modifying the test suite or annotations. 

6. Using IMethodInterceptor

IMethodInterceptor is a TestNG interface that allows us to control which test methods are executed before the test run begins. This mechanism allows us to decide which test methods should be included, skipped, or reordered at the discovery stage itself.

We implement the IMethodInterceptor interface and override the intercept() method. TestNG calls this method once and passes a list of all discovered test methods. Inside the method, we have a collection of test methods we want to skip. This ensures that TestNG never schedules or executes the skipped methods:

public class SkipMethodInterceptor implements IMethodInterceptor {

    private static final Set<String> SKIP_METHODS = Set.of("givenTest_whenFails_thenExecuteSelectively");

    @Override
    public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) {
        return methods.stream()
                .filter(m -> !SKIP_METHODS.contains(m.getMethod().getMethodName()))
                .collect(Collectors.toList());
    }
}

To skip the givenTest_whenFails_thenExecuteSelectively test, we need to attach this interceptor to our tests by registering it with TestNG. We can annotate the test class using @Listeners and reference the interceptor class directly, like this:

@Listeners(SkipMethodInterceptor.class)
public class ExecuteSelectivelyUnitTest {
    // tests here
}

 This approach allows us to avoid executing unnecessary setup logic and keep test selection logic centralized and flexible.

7. IDE-Driven Selective Execution

Modern Java test frameworks and IDEs seamlessly work together. We can run specific tests at the method or class level directly from the IDE. We don’t need to modify the suite files or add any configuration. 

In IntelliJ IDEA, we can run a specific TestNG test directly from the editor, instead of modifying the testng.xml. We need to open the test class, place the cursor on the method annotated with @Test, and click the green icon in the gutter or right-click and select Run, as shown in the image:

Run Exclusive Test

This approach requires no setup, no group annotations, or no suite changes. It allows us to iterate quickly, debug failures immediately, and validate fixes without affecting other tests in the suite.

8. Conclusion

In this article, we discussed various approaches to executing tests selectively in TestNG. 

We saw how TestNG supports selective execution using testng-failed.xml and <include> in testng.xml. These are effective for re-running failures and controlling execution in CI pipelines. Maven Surefire’s single-test execution further enhances this by using command-line-driven reruns without modifying the suite files.

IntelliJ’s IDE-driven execution is the most commonly used approach due to zero setup, fast, and built-in debugging. When more flexibility is required, IMethodInterceptor and @BeforeMethod enable pre-execution filtering and a simple way to isolate tests during debugging.

As always, the code is available over on GitHub.

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)