Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober 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

JUnit Test Cases: How to Write and Run Them

Write a first JUnit Jupiter test, understand assertions and lifecycle methods, add parameterized inputs, and run tests with an IDE, Gradle, Maven, or the Console Launcher.

Free tools Windows power users keep installed

One-click scans. No signup required.

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

A JUnit test is a Java method marked with @Test that calls code you want to check and uses an assertion to verify the result. For a new test, use JUnit Jupiter, put the test under the test source set, and run it from your IDE or build tool. Here is a complete minimal example:

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

class CalculatorTest {
    @Test
    void addsTwoNumbers() {
        Calculator calculator = new Calculator();
        assertEquals(2, calculator.add(1, 1));
    }
}

This assumes a production class named Calculator with an add(int, int) method, and a project configured to compile and run Jupiter tests. The JUnit 5.12.0 User Guide documents the pattern and the execution options below.

What the test does

@Test tells JUnit Jupiter that addsTwoNumbers is a test method. The method creates its input, calls the production code, and checks the outcome. A test should make the behavior under test and the expected result easy to recognize.

assertEquals(expected, actual) compares the expected value with the value returned by the code. If they differ, the assertion fails and the test is reported as failed. Choose an assertion that matches the behavior: equality for values, a truth assertion for a condition, or an exception assertion when an operation is expected to throw. Keep expected and actual in that order for assertEquals.

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.

Place the test in the project

Use the test source set rather than the production source directory. In a conventional Java project, the paths are:

  • Production class: src/main/java/Calculator.java
  • Test class: src/test/java/CalculatorTest.java

Packages should correspond. If Calculator declares a package, give CalculatorTest the matching package declaration or import the production class as appropriate. The test class name ending in Test is a familiar convention and is commonly recognized by build tooling, but discovery also depends on the project’s configured test engine and plugins.

Understand JUnit 5’s pieces

JUnit 5 is organized into three parts: Jupiter is the programming model and extension API for writing modern tests; the JUnit Platform discovers test engines and launches tests; Vintage is an engine that lets the Platform run JUnit 3 and JUnit 4 tests. For a new Jupiter test, the imports must be org.junit.jupiter.api.Test and Jupiter assertions—not the older JUnit 4 org.junit.Test.

The JUnit 5.12.0 guide documents Java 8 or later as its runtime requirement. Compatibility can differ by JUnit release and by the rest of a project’s toolchain, so check the guide for the exact release you select rather than assuming an older dependency version is suitable for a newer project.

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

Configure dependencies and the test runner

Test source code needs the Jupiter API at compile time and a Jupiter engine at runtime. Build configuration syntax and plugin behavior vary by project and release. The JUnit 5.12.0 guide recommends using the JUnit BOM to align JUnit 5 artifact versions when you manage those dependencies yourself. If a framework such as Spring Boot manages JUnit dependencies, follow that framework’s dependency management instead of overriding versions casually.

Gradle

Configure the Gradle test task to use the JUnit Platform. In a Groovy build script:

test {
    useJUnitPlatform()
}

The Kotlin DSL has different syntax; use the Kotlin example in the versioned JUnit guide rather than pasting Groovy syntax into a .gradle.kts file. Ensure the project’s dependencies include the Jupiter components needed to compile and execute tests, with versions aligned as described above. Run the wrapper task from the project root:

./gradlew test

On Windows, use gradlew.bat test. The wrapper uses the Gradle version selected by the project.

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

Maven

Maven projects also need JUnit dependencies and a test plugin configuration that discovers the chosen JUnit generation. Do not copy an old Surefire plugin coordinate from an unrelated tutorial: check the project’s current configuration and the official JUnit guide and starter project for a compatible setup. Run tests from the project root with:

Rank #4
Sale
./mvnw test

Use mvnw.cmd test on Windows when the project includes the Maven wrapper.

Run tests from your IDE, build tool, or console

Where you work Best use What to expect
IDE Running one test or class while developing Use the IDE’s test gutter icon or test-run command. The IDE must support the project’s JUnit generation and resolve its test dependencies.
Build tool Repeatable project runs and continuous integration Run the Gradle or Maven test task through the project wrapper. This exercises the build’s configured discovery and dependencies.
JUnit Console Launcher Running tests where an editor does not provide Platform support The official guide documents the Console Launcher as another Platform execution route; configure its classpath and engine according to the selected JUnit release.

For ongoing work, the IDE is convenient for a focused test and the wrapper task provides a repeatable project-level command suitable for local automation and CI. The Console Launcher is a documented alternative, not a replacement for a correct project build configuration.

Add setup and cleanup only when needed

Use lifecycle methods when a test needs a fresh fixture or a resource must be released. Jupiter’s @BeforeEach runs before each test method, and @AfterEach runs after each test method. For example, a shared setup can create a new calculator before each test:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

class CalculatorTest {
    private Calculator calculator;

    @BeforeEach
    void setUp() {
        calculator = new Calculator();
    }

    @Test
    void addsTwoNumbers() {
        // Exercise calculator and assert the result.
    }
}

Use @BeforeAll or @AfterAll only for class-level setup or cleanup that genuinely should happen once for the test class. Under the default lifecycle, those methods must be static; Jupiter also documents conditions for using non-static methods with a different test-instance lifecycle. Check the guide before changing lifecycle configuration, especially when tests share mutable state.

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

Reuse a test with parameterized inputs

Parameterized tests run a test method multiple times with different arguments. The JUnit 5 User Guide puts it this way: “Parameterized tests make it possible to run a test method multiple times with different arguments.” A parameterized test needs an argument source and the junit-jupiter-params artifact in addition to the relevant Jupiter setup.

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class CalculatorTest {
    @ParameterizedTest
    @CsvSource({ "1, 1, 2", "2, 3, 5", "-1, 1, 0" })
    void addsNumbers(int left, int right, int expected) {
        Calculator calculator = new Calculator();
        assertEquals(expected, calculator.add(left, right));
    }
}

Here each CSV row supplies two operands and the expected sum. Prefer a small set of representative cases that clarify behavior, including boundaries or negative values when relevant. Parameterized testing is useful when the same rule should hold across inputs; separate tests can be clearer when scenarios have materially different setup or intent.

Troubleshoot tests that do not run

  • The IDE reports no tests: confirm the file is under the project’s test source set, the test class is part of the module, and test dependencies have been imported or refreshed.
  • The test compiles but is not discovered: verify the project has a Jupiter engine and the build is configured for the JUnit Platform. In Gradle, check that useJUnitPlatform() is in the test task.
  • An annotation or assertion import cannot be resolved: confirm the Jupiter API dependency is present and that the imports use org.junit.jupiter.api. Do not mix JUnit 4’s org.junit.Test with Jupiter annotations in a beginner Jupiter example.
  • Legacy JUnit 4 tests disappear after a migration: the Platform needs the Vintage engine to run JUnit 3 or JUnit 4 tests. Add it only if legacy tests must continue to run; new tests can use Jupiter directly.
  • Gradle or Maven behaves differently from the IDE: the build runner may have different dependencies, plugin configuration, or discovery rules. Run the wrapper task and inspect its test output, then reconcile the project configuration rather than assuming IDE execution proves the build is configured.
  • Parameterized annotations cannot be resolved: add the JUnit Jupiter parameters artifact and ensure the argument-source imports match Jupiter.

Or skip the browser setup

For an unrelated but useful developer utility, ScreenshotNeo is a website screenshot API and MCP server; it does not run JUnit tests. Its API can return a screenshot or PDF with one GET request. Example cURL call (replace the target URL as needed):

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

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
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. Cookie banners, popups and chat widgets are removed before the shot; bot checks, blank pages and failed loads are never billed. An MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for free.

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 *

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
Crashes, No Sound, or Screen Glitches?Free driver scan
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.