DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk6 min

How to Write and Run Test Cases in Java with JUnit, Maven, and Gradle

Create a JUnit Jupiter test and run it through your project's Maven or Gradle build, with setup steps and fixes for common discovery problems.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Write a Java test as a method marked with JUnit Jupiter’s @Test, put it in the project’s test source set, and run it through the build tool the project already uses. With Maven, that is commonly mvn test; with Gradle, it is commonly ./gradlew test. The code must have JUnit’s test API to compile and a test engine and build-tool integration to execute tests.

Write a basic Java test with JUnit Jupiter

A test case states an expected outcome and checks it against the result produced by the code. JUnit Jupiter uses an ordinary Java method marked @Test, with assertions such as assertEquals to check behavior.

As an Amazon Associate I earn from qualifying purchases.

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

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

This example passes because the expected value, 4, equals the actual expression, 2 + 2. In a project, replace the expression with a call to the behavior you want to check. Give test methods names that make the behavior clear, and keep each test understandable and independent where practical.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The class is package-private here; JUnit Jupiter supports this simple form. The example requires JUnit Jupiter’s API to compile and an engine configured by the build to run. The JUnit User Guide documents the foundational annotation and assertion pattern; because that page is an early milestone guide, do not copy its old dependency versions into a current project.

Choose the build workflow already in your project

Use Maven if the repository has a pom.xml; use Gradle if it has build.gradle or build.gradle.kts. Both can compile and execute tests, filter test runs, and produce reports. The documentation does not establish a universal performance or quality winner, so the practical choice is the build tool already configured in the repository and familiar to its team.

Question Maven Gradle
Usual test source location src/test/java, unless the project configures another source root The Java plugin’s test source set
Typical full test command mvn test ./gradlew test when the wrapper is present
JUnit Platform setup Surefire configuration and a runtime test engine Jupiter test dependencies and useJUnitPlatform()
Targeted execution Surefire supports -Dtest=ClassName; behavior depends on plugin configuration Use the test task’s filtering options

Write and run tests with Maven

1. Add JUnit for tests

Add JUnit Jupiter as a test-scoped dependency in pom.xml. The Surefire JUnit Platform documentation requires a test engine implementation at test runtime; the API alone may let source code compile without making tests executable. Follow the dependency and Surefire configuration documented for the versions actually used by your project rather than pasting in a historical version pin.

2. Put the test in the test source tree

By convention, Maven compiles test code from src/test/java. Mirror the package path of the class under test when that makes the project easier to navigate. If the project changes its source roots, use its configured location instead.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Run the lifecycle or select a class

From the directory containing pom.xml, run the test lifecycle:

mvn test

For a focused run, Surefire documents selecting a class with:

mvn -Dtest=CalculatorTest test

Check the project’s Surefire version and settings if selection behaves differently; plugin configuration can affect discovery and execution.

4. Read the test result, not just the compile result

Review Maven’s test summary and generated reports for failures, errors, skips, or a zero-test result. Successful compilation only shows that the code compiled; it does not prove that the intended tests were discovered and executed. See the Maven Surefire JUnit Platform documentation for platform setup, discovery, and selection details.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Write and run tests with Gradle

1. Configure Jupiter dependencies and the platform

The Gradle 9.8.0 Java testing guide shows Jupiter as a testImplementation dependency and the JUnit Platform launcher as a testRuntimeOnly dependency. Configure the test task to use the platform:

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter:YOUR_VERSION")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

This Kotlin DSL example marks the version as a value to supply, not a literal dependency version. Use versions compatible with the project’s Java and Gradle configuration; do not treat the documentation’s dependency example as a reason to override an existing version catalog or dependency-management setup. In a Groovy DSL build file, the syntax differs, but the configuration roles are the same.

Rank #4
Sale

2. Use the test source set and run the task

The Java plugin supplies a test source set, associated classpaths, and a test task. Put the class in that source set, then run:

./gradlew test

The wrapper command uses the Gradle version selected by the repository. On Windows, use gradlew.bat test. Use an installed gradle test only if the project does not provide a wrapper or your team directs you to use a compatible installation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

3. Filter and inspect reports

For a narrow investigation, use Gradle test filtering and logging rather than changing the test’s logic just to isolate it. Inspect the test task’s results and reports to see what ran and which tests failed or were skipped. The Gradle 9.8.0 Java testing guide covers source sets, filtering, logging, reporting, and troubleshooting.

Best Value
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Troubleshoot tests that do not run

  • No tests found: Confirm the file is in the configured test source set, its class and method names meet the build tool’s discovery rules, and no include, exclude, or filter setting removes it. Maven Surefire documents default name patterns and configurable discovery rules.
  • @Test or assertions do not compile: Check that the JUnit API is on the test compile classpath and declared with the build tool’s test dependency configuration.
  • Tests compile but do not execute: Check for a runtime engine and compatible runner/platform integration. Maven’s JUnit Platform setup explicitly requires an engine; for Gradle, verify Jupiter dependencies and that the test task calls useJUnitPlatform().
  • JUnit 4 tests disappear after a platform migration: In the documented Surefire JUnit Platform setup, JUnit 4 tests run through the Vintage engine, and the current Surefire documentation identifies JUnit 4.12 as the minimum supported version for that setup. Confirm the project’s actual Surefire version, engine, and dependencies before changing them.
  • The command-line build and IDE disagree: Compare the JDK, project build configuration, and resolved dependencies used by each. IDE-specific behavior depends on the IDE and project setup; the build-tool configuration is the reference for a reproducible command-line run.
  • Build succeeds but the expected test failed or was skipped: Read the test summary and reports, verify that the test was discovered, and distinguish failures from skips or errors. A successful compile alone is not a passing test run.

Or skip the browser setup

If your Java workflow also needs screenshots of pages for documentation or visual checks, ScreenshotNeo offers a GET API call rather than requiring you to configure a browser capture stack. Its clean-shot flow accepts cookie consent and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be disabled. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers report the page verdict and billing status. An MCP server exposes screenshot and PDF capture tools to AI agents.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. The free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo or sign up free.

Frequently Asked Questions

Can I write Java tests without JUnit?

This guide covers JUnit Jupiter because it is the framework documented in the cited setup sources; other testing frameworks require their own dependencies and runner configuration.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my test pass in the IDE but not in CI?

Compare the JDK, build configuration, dependency resolution, and test filters used in both environments, then inspect the CI test reports to confirm discovery and execution.

Quick Recap

SaleBestseller No. 3
SaleBestseller No. 4
Pragmatic Unit Testing in Java with JUnit
Pragmatic Unit Testing in Java with JUnit
Used Book in Good Condition
$15.01
SaleBestseller No. 5

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.