How do I test private logic without testing private methods directly?

The best way to test private logic is to test the observable behavior that depends on it, usually through the class’s public methods.

Private methods are implementation details. If you test them directly, your tests become tightly coupled to how the class is written internally. That makes refactoring harder because changing a private method can break tests even when the public behavior still works correctly.

Short Answer

Do not test private methods directly.

Instead:

Test the public behavior that uses the private logic.

If a private method contains important logic, make sure that logic is covered by tests through the public API.


Example

Suppose you have a class like this:

public class DiscountService {

    public BigDecimal calculateFinalPrice(Customer customer, BigDecimal price) {
        if (isEligibleForDiscount(customer)) {
            return price.multiply(new BigDecimal("0.90"));
        }

        return price;
    }

    private boolean isEligibleForDiscount(Customer customer) {
        return customer.isActive()
                && customer.getOrdersCount() >= 5
                && !customer.isBlacklisted();
    }
}

You do not need to test isEligibleForDiscount() directly.

Instead, test calculateFinalPrice() with different inputs.

import org.junit.jupiter.api.Test;

import java.math.BigDecimal;

import static org.junit.jupiter.api.Assertions.assertEquals;

class DiscountServiceTest {

    private final DiscountService discountService = new DiscountService();

    @Test
    void calculateFinalPriceAppliesDiscountForEligibleCustomer() {
        Customer customer = new Customer(true, 5, false);

        BigDecimal result = discountService.calculateFinalPrice(
                customer,
                new BigDecimal("100.00")
        );

        assertEquals(new BigDecimal("90.0000"), result);
    }

    @Test
    void calculateFinalPriceDoesNotApplyDiscountForInactiveCustomer() {
        Customer customer = new Customer(false, 5, false);

        BigDecimal result = discountService.calculateFinalPrice(
                customer,
                new BigDecimal("100.00")
        );

        assertEquals(new BigDecimal("100.00"), result);
    }

    @Test
    void calculateFinalPriceDoesNotApplyDiscountForBlacklistedCustomer() {
        Customer customer = new Customer(true, 5, true);

        BigDecimal result = discountService.calculateFinalPrice(
                customer,
                new BigDecimal("100.00")
        );

        assertEquals(new BigDecimal("100.00"), result);
    }
}

The private method is still tested indirectly because each test verifies a public result caused by the private logic.


Why Not Test Private Methods Directly?

Testing private methods directly usually causes problems:

Problem Explanation
Tests become fragile Renaming or reorganizing private methods breaks tests unnecessarily.
Refactoring becomes harder You may avoid improving code because tests depend on internals.
Tests focus on implementation Good tests should focus on behavior and outcomes.
Private methods may disappear A private helper may be merged, split, renamed, or replaced.

A good unit test should answer:

Given this input, what result or behavior should the class produce?

Not:

Which private helper method did the class use internally?


What If the Private Method Has Complex Logic?

If a private method is complex enough that you strongly want to test it directly, that is often a design signal.

You have a few better options.


Option 1: Test It Through Public Scenarios

This is usually the best option.

For example, if the private method has three rules, write public tests that trigger each rule.

@Test
void calculateFinalPriceDoesNotApplyDiscountWhenCustomerHasTooFewOrders() {
    Customer customer = new Customer(true, 4, false);

    BigDecimal result = discountService.calculateFinalPrice(
            customer,
            new BigDecimal("100.00")
    );

    assertEquals(new BigDecimal("100.00"), result);
}

You are still covering the private logic, but your test remains focused on business behavior.


Option 2: Extract the Logic into a Separate Class

If the private logic is significant, reusable, or independently meaningful, extract it into its own class and test that class through its public method.

public class DiscountEligibilityPolicy {

    public boolean isEligible(Customer customer) {
        return customer.isActive()
                && customer.getOrdersCount() >= 5
                && !customer.isBlacklisted();
    }
}

Then your service becomes simpler:

public class DiscountService {

    private final DiscountEligibilityPolicy eligibilityPolicy;

    public DiscountService(DiscountEligibilityPolicy eligibilityPolicy) {
        this.eligibilityPolicy = eligibilityPolicy;
    }

    public BigDecimal calculateFinalPrice(Customer customer, BigDecimal price) {
        if (eligibilityPolicy.isEligible(customer)) {
            return price.multiply(new BigDecimal("0.90"));
        }

        return price;
    }
}

Now you can test the policy directly:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class DiscountEligibilityPolicyTest {

    private final DiscountEligibilityPolicy policy = new DiscountEligibilityPolicy();

    @Test
    void isEligibleReturnsTrueForActiveCustomerWithEnoughOrders() {
        Customer customer = new Customer(true, 5, false);

        assertTrue(policy.isEligible(customer));
    }

    @Test
    void isEligibleReturnsFalseForBlacklistedCustomer() {
        Customer customer = new Customer(true, 5, true);

        assertFalse(policy.isEligible(customer));
    }
}

This is often the cleanest solution when the private method represents a real business rule.


Option 3: Use Package-Private Carefully

Sometimes you can make a helper method package-private instead of private and test it from a test class in the same package.

boolean isEligibleForDiscount(Customer customer) {
    return customer.isActive()
            && customer.getOrdersCount() >= 5
            && !customer.isBlacklisted();
}

But use this sparingly.

Only do this when:

  • the method represents meaningful behavior,
  • extracting a new class would be excessive,
  • and exposing it within the package does not harm the design.

Do not make methods less private just because testing through the public API is inconvenient.


Avoid Reflection for Private Method Testing

Technically, Java reflection can call private methods, but it is usually a bad idea for unit tests.

Avoid this style:

Method method = DiscountService.class.getDeclaredMethod(
        "isEligibleForDiscount",
        Customer.class
);
method.setAccessible(true);

boolean result = (boolean) method.invoke(discountService, customer);

This works, but it makes the test depend on implementation details. It also becomes noisy, fragile, and harder to maintain.

Use reflection for framework-level tools or special cases, not ordinary unit tests.


A Practical Rule

When you see private logic, ask:

  1. Can I observe its effect through a public method?
    Test through the public method.

  2. Is the private logic complex or independently meaningful?
    Extract it into a separate class and test that class.

  3. Is it just a small helper?
    Do not test it directly. Test the behavior it supports.

  4. Am I tempted to use reflection?
    Usually stop and reconsider the design.


Summary

You test private logic by testing the public behavior that uses it.

Use this guideline:

Situation Recommended approach
Private helper supports public behavior Test through the public method
Private logic has branches or edge cases Cover those cases via public inputs
Private logic is complex business logic Extract it into a separate class
Helper is useful only inside the class Keep it private
You need reflection to test it Usually avoid it

The goal is not to test every method. The goal is to test the behavior your code promises to provide.

How do I test code that depends on time?

Code that depends directly on the current date or time can be difficult to test because the result changes every time the test runs.

For example, code like this is hard to test reliably:

import java.time.LocalDate;

public class SubscriptionService {
    public boolean isExpired(LocalDate expiryDate) {
        return expiryDate.isBefore(LocalDate.now());
    }
}

The problem is LocalDate.now().
Today’s test result may be different from tomorrow’s.

The best solution is to avoid calling the system clock directly inside your business logic. Instead, inject a time source, usually java.time.Clock.


Using Clock in Production Code

Java’s java.time.Clock lets you control what “now” means.

import java.time.Clock;
import java.time.LocalDate;

public class SubscriptionService {
    private final Clock clock;

    public SubscriptionService(Clock clock) {
        this.clock = clock;
    }

    public boolean isExpired(LocalDate expiryDate) {
        LocalDate today = LocalDate.now(clock);
        return expiryDate.isBefore(today);
    }
}

Now the class no longer depends directly on the real system date.
Instead, it depends on a Clock.


Using the Real Clock in Application Code

In normal application code, pass the system clock:

import java.time.Clock;

public class Application {
    public static void main(String[] args) {
        SubscriptionService service =
                new SubscriptionService(Clock.systemDefaultZone());

        // Use the service normally
    }
}

You can also use UTC if your application should not depend on the server’s local timezone:

Clock.systemUTC()

Testing with a Fixed Clock

In tests, use Clock.fixed(...) to make time predictable.

import org.junit.jupiter.api.Test;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

class SubscriptionServiceTest {

    @Test
    void isExpiredReturnsTrueWhenExpiryDateIsBeforeToday() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T10:00:00Z"),
                ZoneId.of("UTC")
        );

        SubscriptionService service = new SubscriptionService(fixedClock);

        boolean expired = service.isExpired(LocalDate.of(2026, 7, 12));

        assertTrue(expired);
    }

    @Test
    void isExpiredReturnsFalseWhenExpiryDateIsToday() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T10:00:00Z"),
                ZoneId.of("UTC")
        );

        SubscriptionService service = new SubscriptionService(fixedClock);

        boolean expired = service.isExpired(LocalDate.of(2026, 7, 13));

        assertFalse(expired);
    }

    @Test
    void isExpiredReturnsFalseWhenExpiryDateIsAfterToday() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T10:00:00Z"),
                ZoneId.of("UTC")
        );

        SubscriptionService service = new SubscriptionService(fixedClock);

        boolean expired = service.isExpired(LocalDate.of(2026, 7, 14));

        assertFalse(expired);
    }
}

Now the tests are stable because “today” is always 2026-07-13.


Testing Date and Time Logic

The same approach works with LocalDateTime, ZonedDateTime, Instant, and other classes from the java.time package.

Example:

import java.time.Clock;
import java.time.LocalDateTime;

public class GreetingService {
    private final Clock clock;

    public GreetingService(Clock clock) {
        this.clock = clock;
    }

    public String greeting() {
        int hour = LocalDateTime.now(clock).getHour();

        if (hour < 12) {
            return "Good morning";
        }

        if (hour < 18) {
            return "Good afternoon";
        }

        return "Good evening";
    }
}

Test:

import org.junit.jupiter.api.Test;

import java.time.Clock;
import java.time.Instant;
import java.time.ZoneId;

import static org.junit.jupiter.api.Assertions.assertEquals;

class GreetingServiceTest {

    @Test
    void greetingReturnsGoodMorningBeforeNoon() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T08:00:00Z"),
                ZoneId.of("UTC")
        );

        GreetingService service = new GreetingService(fixedClock);

        assertEquals("Good morning", service.greeting());
    }

    @Test
    void greetingReturnsGoodAfternoonAfterNoon() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T14:00:00Z"),
                ZoneId.of("UTC")
        );

        GreetingService service = new GreetingService(fixedClock);

        assertEquals("Good afternoon", service.greeting());
    }

    @Test
    void greetingReturnsGoodEveningInTheEvening() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T20:00:00Z"),
                ZoneId.of("UTC")
        );

        GreetingService service = new GreetingService(fixedClock);

        assertEquals("Good evening", service.greeting());
    }
}

Using Clock with Spring

In a Spring application, you can register a Clock as a bean.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Clock;

@Configuration
public class TimeConfig {

    @Bean
    public Clock clock() {
        return Clock.systemUTC();
    }
}

Then inject it into your service:

import org.springframework.stereotype.Service;

import java.time.Clock;
import java.time.LocalDate;

@Service
public class SubscriptionService {
    private final Clock clock;

    public SubscriptionService(Clock clock) {
        this.clock = clock;
    }

    public boolean isExpired(LocalDate expiryDate) {
        return expiryDate.isBefore(LocalDate.now(clock));
    }
}

In tests, replace the Clock bean with a fixed one:

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

import static org.junit.jupiter.api.Assertions.assertTrue;

class SubscriptionServiceSpringTest {

    @TestConfiguration
    static class FixedClockConfig {
        @Bean
        Clock clock() {
            return Clock.fixed(
                    Instant.parse("2026-07-13T10:00:00Z"),
                    ZoneId.of("UTC")
            );
        }
    }

    @Test
    void isExpiredUsesFixedClock() {
        SubscriptionService service =
                new SubscriptionService(FixedClockConfig.class.cast(null));
    }
}

A simpler unit test usually does not need Spring at all:

import org.junit.jupiter.api.Test;

import java.time.Clock;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;

import static org.junit.jupiter.api.Assertions.assertTrue;

class SubscriptionServiceTest {

    @Test
    void isExpiredUsesFixedClock() {
        Clock fixedClock = Clock.fixed(
                Instant.parse("2026-07-13T10:00:00Z"),
                ZoneId.of("UTC")
        );

        SubscriptionService service = new SubscriptionService(fixedClock);

        assertTrue(service.isExpired(LocalDate.of(2026, 7, 12)));
    }
}

Avoid These Approaches When Possible

Avoid scattering calls like these throughout your code:

LocalDate.now();
LocalDateTime.now();
Instant.now();
System.currentTimeMillis();
new Date();

They make tests harder because the current time cannot easily be controlled.

Also avoid adding arbitrary sleeps to tests:

Thread.sleep(1000);

Tests that depend on sleeping are usually slow and unreliable.


Good Rule of Thumb

Use this rule:

If your code needs the current time, inject a Clock.

This makes your code:

  • easier to test
  • more predictable
  • less dependent on the machine’s timezone
  • easier to reason about
  • safer around midnight and date-boundary bugs

For most Java applications, java.time.Clock is the cleanest way to test code that depends on time.

How do I use assumptions in JUnit tests?

In JUnit 5, assumptions let you run a test only when certain conditions are true. If an assumption fails, the test is skipped/aborted, not failed.

They are useful when a test depends on things like:

  • operating system
  • environment variables
  • external services
  • database availability
  • specific Java version
  • local developer setup

JUnit assumptions are available from:

import static org.junit.jupiter.api.Assumptions.*;

Basic Example

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;

class EnvironmentTest {

    @Test
    void testOnlyRunsOnCiServer() {
        assumeTrue("true".equals(System.getenv("CI")));

        int result = 2 + 3;

        assertEquals(5, result);
    }
}

If the environment variable CI is not set to "true", this test is skipped.

It does not fail.

Using assumeTrue()

assumeTrue() allows the test to continue only if the condition is true.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;

class OperatingSystemTest {

    @Test
    void testOnlyOnLinux() {
        assumeTrue(System.getProperty("os.name").toLowerCase().contains("linux"));

        assertTrue(true);
    }
}

This test only runs on Linux.

Using assumeFalse()

assumeFalse() is the opposite. The test continues only if the condition is false.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumeFalse;
import static org.junit.jupiter.api.Assertions.assertEquals;

class LocalEnvironmentTest {

    @Test
    void testDoesNotRunInProduction() {
        assumeFalse("prod".equals(System.getenv("APP_ENV")));

        assertEquals(4, 2 + 2);
    }
}

If APP_ENV is "prod", the test is skipped.

Adding a Message

You can add a message to explain why the test was skipped.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;

class JavaVersionTest {

    @Test
    void testOnlyOnSpecificJavaVersion() {
        assumeTrue(
                System.getProperty("java.version").startsWith("25"),
                "This test only runs on Java 25"
        );

        assertEquals(10, 5 + 5);
    }
}

The message helps explain the skipped test in the test report.

Using assumingThat()

assumingThat() lets you run only part of a test conditionally.

Unlike assumeTrue(), it does not skip the whole test. It only skips the block of code inside it.

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumingThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

class ConditionalBlockTest {

    @Test
    void testWithConditionalSection() {
        assertEquals(4, 2 + 2);

        assumingThat(
                "dev".equals(System.getenv("APP_ENV")),
                () -> {
                    assertTrue(true);
                    System.out.println("Extra checks for development environment");
                }
        );

        assertEquals(6, 3 + 3);
    }
}

In this example:

  • the first assertion always runs
  • the conditional block runs only when APP_ENV is "dev"
  • the last assertion always runs

Difference Between Assertions and Assumptions

Feature Assertion Assumption
Purpose Verify expected behavior Check whether test should run
If condition fails Test fails Test is skipped
Common methods assertEquals(), assertTrue() assumeTrue(), assumeFalse()
Used for Validating code correctness Checking test prerequisites

Example: Skipping Test If Database Is Not Available

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assumptions.assumeTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;

class DatabaseTest {

    @Test
    void testDatabaseQuery() {
        assumeTrue(isDatabaseAvailable(), "Database is not available");

        String result = "John";

        assertEquals("John", result);
    }

    private boolean isDatabaseAvailable() {
        // In a real test, you might check a connection here.
        return false;
    }
}

Since isDatabaseAvailable() returns false, the test is skipped.

Common Assumption Methods

JUnit 5 provides these commonly used methods:

assumeTrue(condition);
assumeTrue(condition, message);

assumeFalse(condition);
assumeFalse(condition, message);

assumingThat(condition, executable);

When Should You Use Assumptions?

Use assumptions when the test depends on something outside the code being tested.

Good examples:

assumeTrue(System.getenv("CI") != null);
assumeTrue(System.getProperty("os.name").contains("Linux"));
assumeFalse("prod".equals(System.getenv("APP_ENV")));

Avoid using assumptions to hide broken tests. If the code is wrong, use assertions and let the test fail.

Summary

Assumptions in JUnit are used to skip tests when required conditions are not met.

Use:

assumeTrue(condition);

when a test should continue only if a condition is true.

Use:

assumeFalse(condition);

when a test should continue only if a condition is false.

Use:

assumingThat(condition, () -> {
    // conditional checks
});

when only part of a test should run conditionally.

How do I write repeated tests in JUnit?

In JUnit 5, repeated tests are written using the @RepeatedTest annotation.

A repeated test runs the same test method multiple times without requiring different input values.

Basic Example

import org.junit.jupiter.api.RepeatedTest;

import static org.junit.jupiter.api.Assertions.assertTrue;

class RandomNumberTest {

    @RepeatedTest(5)
    void randomNumberShouldBeLessThanTen() {
        int number = (int) (Math.random() * 10);

        assertTrue(number >= 0 && number < 10);
    }
}

This test runs 5 times.

Difference Between @Test and @RepeatedTest

Instead of writing:

import org.junit.jupiter.api.Test;

class ExampleTest {

    @Test
    void shouldRunOnce() {
        // test logic
    }
}

You write:

import org.junit.jupiter.api.RepeatedTest;

class ExampleTest {

    @RepeatedTest(3)
    void shouldRunThreeTimes() {
        // test logic
    }
}

Access the Current Repetition

JUnit can inject a RepetitionInfo parameter into a repeated test. This lets you know which repetition is currently running.

import org.junit.jupiter.api.RepeatedTest;
import org.junit.jupiter.api.RepetitionInfo;

import static org.junit.jupiter.api.Assertions.assertTrue;

class RetryExampleTest {

    @RepeatedTest(5)
    void repeatedTestWithInfo(RepetitionInfo repetitionInfo) {
        int current = repetitionInfo.getCurrentRepetition();
        int total = repetitionInfo.getTotalRepetitions();

        System.out.println("Running repetition " + current + " of " + total);

        assertTrue(current >= 1);
        assertTrue(current <= total);
    }
}

Example output:

Running repetition 1 of 5
Running repetition 2 of 5
Running repetition 3 of 5
Running repetition 4 of 5
Running repetition 5 of 5

Customize the Display Name

You can customize the name shown for each repeated test invocation.

import org.junit.jupiter.api.RepeatedTest;

class LoginTest {

    @RepeatedTest(value = 3, name = "Login attempt {currentRepetition} of {totalRepetitions}")
    void loginShouldSucceedRepeatedly() {
        // test login logic
    }
}

This may display as:

Login attempt 1 of 3
Login attempt 2 of 3
Login attempt 3 of 3

Common placeholders are:

{displayName}
{currentRepetition}
{totalRepetitions}

JUnit also provides predefined formats:

@RepeatedTest(value = 3, name = RepeatedTest.SHORT_DISPLAY_NAME)

or:

@RepeatedTest(value = 3, name = RepeatedTest.LONG_DISPLAY_NAME)

Example with @BeforeEach

Lifecycle methods such as @BeforeEach run before each repetition.

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.RepeatedTest;

import static org.junit.jupiter.api.Assertions.assertEquals;

class CounterTest {

    private int counter;

    @BeforeEach
    void setUp() {
        counter = 0;
    }

    @RepeatedTest(3)
    void counterStartsAtZeroEachTime() {
        assertEquals(0, counter);

        counter++;
    }
}

Because @BeforeEach runs before every repetition, the counter starts at 0 each time.

When to Use Repeated Tests

Use @RepeatedTest when you want to run the same test multiple times, for example:

  • testing code that uses random values
  • checking for flaky behavior
  • verifying repeated operations
  • testing concurrency-related code
  • making sure state is reset between runs

@RepeatedTest vs Parameterized Tests

Use @RepeatedTest when the test logic is the same and the input does not change.

Use parameterized tests when you want to run the same test with different inputs.

@RepeatedTest(5)
void sameTestRepeatedSeveralTimes() {
    // same input or generated input each time
}
@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void sameTestWithDifferentValues(int value) {
    // runs once for each value
}

Maven Dependency

Make sure JUnit Jupiter is available in your project:

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>5.13.4</version>
    <scope>test</scope>
</dependency>

Gradle Dependency

testImplementation 'org.junit.jupiter:junit-jupiter:5.13.4'

test {
    useJUnitPlatform()
}

Summary

Use @RepeatedTest to run the same test multiple times:

import org.junit.jupiter.api.RepeatedTest;

class ExampleTest {

    @RepeatedTest(5)
    void shouldRunFiveTimes() {
        // test logic
    }
}

A repeated test is useful when you need the same test executed more than once, while a parameterized test is better when each run needs different input data.

How do I run only selected JUnit tests by tag?

To run only selected JUnit 5 tests by tag, mark your tests with @Tag, then configure your build tool or IDE to include only that tag.

1. Add tags to your tests

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

class PaymentServiceTest {

    @Test
    @Tag("fast")
    void calculatesTotal() {
        // test code
    }

    @Test
    @Tag("integration")
    void connectsToPaymentGateway() {
        // test code
    }
}

You can also tag an entire test class:

import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

@Tag("integration")
class UserRepositoryTest {

    @Test
    void savesUser() {
        // test code
    }
}

All tests in that class inherit the integration tag.


2. Run tagged tests with Maven

If you use Maven Surefire, run tests with a specific tag like this:

mvn test -Dgroups=integration

To run multiple tags:

mvn test -Dgroups="fast,integration"

To exclude a tag:

mvn test -DexcludedGroups=slow

Example Maven configuration:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.5.2</version>
        </plugin>
    </plugins>
</build>

3. Run tagged tests with Gradle

For Gradle, configure the test task:

tasks.test {
    useJUnitPlatform {
        includeTags 'integration'
    }
}

Then run:

gradle test

You can include multiple tags:

tasks.test {
    useJUnitPlatform {
        includeTags 'fast', 'integration'
    }
}

Or exclude tags:

tasks.test {
    useJUnitPlatform {
        excludeTags 'slow'
    }
}

You can also pass tags from the command line:

tasks.test {
    useJUnitPlatform {
        if (project.hasProperty('includeTags')) {
            includeTags project.property('includeTags').split(',')
        }
    }
}

Then run:

gradle test -PincludeTags=integration

4. Run tagged tests in IntelliJ IDEA

In IntelliJ IDEA:

  1. Open Run | Edit Configurations…
  2. Create or select a JUnit run configuration.
  3. Set Test kind to Tags.
  4. Enter the tag name, for example:
    integration
    
  5. Run the configuration.

    You can use tag expressions such as:

    fast & !slow
    

    or:

    integration | smoke
    

Summary

Tool Example
JUnit annotation @Tag("integration")
Maven mvn test -Dgroups=integration
Gradle includeTags 'integration'
IntelliJ IDEA JUnit run configuration → Test kind: Tags

Use tags like fast, slow, unit, integration, or smoke to organize your test suite and run only the tests you need.