How To Execute Classes and Packages in JUnit 5

:rocket: JUnit 5 Tutorial – Part 8 is LIVE!

In this session, join Rex Jones – QA Engineer, Trainer, YouTuber & Blogger – as he walks you through executing packages and classes in JUnit 5 using Maven.

:white_check_mark: Learn how to:

  • Run all classes and packages in JUnit 5
  • Target a specific class or package for faster test execution
  • Improve your workflow efficiency with Maven

:pushpin: Perfect for testers, developers, and anyone leveling up their JUnit 5 skills.

:point_right: Watch now:

I often just need to run one test class while developing, and JUnit 5 makes this easy.

How I do it:

Make sure your class is annotated with @Test methods:

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

public class CalculatorTest {
    @Test
    void additionTest() {
        assertEquals(4, 2 + 2);
    }
}

Run the class directly:

In IntelliJ, right-click the class β†’ Run 'CalculatorTest'.

Or use Maven/Gradle CLI:

mvn test -Dtest=CalculatorTest

or

./gradlew test --tests "CalculatorTest"

This is my go-to when I’m working on a single moduleβ€”it’s quick and precise.

Hi! Sometimes I want to run all tests in a package without touching each class individually. JUnit 5 supports this nicely.

How I do it:

Organize your tests under a package, e.g., com.myapp.tests.

Use your IDE’s package runner:

IntelliJ: Right-click the package β†’ Run 'tests in com.myapp.tests'.

Maven:

mvn test -Dtest=com.myapp.tests.*

Gradle:

./gradlew test --tests "com.myapp.tests.*"

This way, I can run all related tests together, which is super handy before a commit.

For more control over which classes run together, I create a JUnit 5 test suite.

Example:

import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;

@Suite
@SelectClasses({CalculatorTest.class, MathUtilsTest.class})
public class AllTestsSuite {
}

Run AllTestsSuite like a normal class, and it executes all selected test classes.

Works with IDE, Maven, and Gradle.

Great for grouping specific feature tests or integration tests.

I personally use suites when preparing a release build, it ensures all critical tests run without relying on package scanning.