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.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Clear out junk files and repair common Windows errorsFree Scan →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →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.
#1 Best Overall
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.
Rank #2
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.
Rank #3
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.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteWrite 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
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.
Recommended Free Tools
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
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.
@Testor 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.
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
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.




