Java JUnit Basics

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 249 of 306

JUnit is the standard unit testing framework for Java. A unit test is a small piece of code that calls one method of your program with known input and checks that the result is what you expect. When every important method has tests, you can change code with confidence, because a broken feature shows up as a failing test within seconds.

This lesson introduces JUnit basics with JUnit 6, the current version: how the framework is organized, how to add it to a Maven or Gradle project, how to write and run your first test, and how to read a failing test report. It ends with a tested grade calculator. The next lessons go deeper into Java Test Methods and JUnit Assertions.


What Is JUnit and Why Use It

Without tests, you check code by running the program and looking at the output by eye. That works once, but nobody repeats it after every change. A JUnit test does the same check automatically, every time you build.

Manual checkingJUnit testing
Run main, read the consoleRun all tests with one command
You remember what "correct" looks likeThe expected value is written in the test
Slow to repeat, easy to skipRuns on every build, in seconds
A broken feature may go unnoticedA failing test names the exact method and value

JUnit 6 is made of three parts:

ModuleWhat it does
JUnit PlatformLaunches tests and reports results; used by Maven, Gradle and IDEs
JUnit JupiterThe API you write tests with: @Test, Assertions, @BeforeEach and more
JUnit VintageRuns old JUnit 3 and 4 tests (deprecated in JUnit 6)

Note: JUnit 6 was released in September 2025 and requires Java 17 or newer. All three modules now share one version number, such as 6.1.3. If you know JUnit 5, the test code is the same: the packages are still org.junit.jupiter.api.


Add JUnit to a Maven Project

Tests live in a separate source folder, so they are compiled and run during the build but never packaged into your application JAR.

grade-app/
├── pom.xml
└── src/
    ├── main/java/com/gocourse/Calculator.java       (application code)
    └── test/java/com/gocourse/CalculatorTest.java   (test code)

Add the JUnit Jupiter dependency with test scope, and a recent Surefire plugin, which is the Maven plugin that runs tests:

<properties>
    <maven.compiler.release>21</maven.compiler.release>
</properties>

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

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

How it works:

  • junit-jupiter is an aggregate artifact. It pulls in the Jupiter API for writing tests, the Jupiter engine for running them, and parameterized-test support.
  • <scope>test</scope> makes JUnit available only to code under src/test/java. Your production code cannot accidentally depend on it.
  • Surefire 3.x detects the JUnit Platform automatically, so no extra configuration is needed.

For Gradle, use the JUnit BOM so every JUnit artifact gets the same version:

// build.gradle.kts
dependencies {
    testImplementation(platform("org.junit:junit-bom:6.1.3"))
    testImplementation("org.junit.jupiter:junit-jupiter")
    testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}

tasks.test {
    useJUnitPlatform()
}

How it works:

  • platform("org.junit:junit-bom:6.1.3") imports the bill of materials, so the following JUnit lines need no version.
  • useJUnitPlatform() tells Gradle's test task to run tests through the JUnit Platform. Without it, Gradle finds no JUnit Jupiter tests.

Note: You will learn more about these build tools in Maven Basics and Gradle Basics. For this lesson, copying the snippets is enough.


Write Your First JUnit Test

Start with a small class to test:

package com.gocourse;

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }

    public int subtract(int a, int b) {
        return a - b;
    }

    public double divide(int dividend, int divisor) {
        if (divisor == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return (double) dividend / divisor;
    }
}

A test class usually has the same name plus Test and sits in the same package under src/test/java. Each test is a method marked with @Test.

package com.gocourse;

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

import org.junit.jupiter.api.Test;

class CalculatorTest {

    private final Calculator calculator = new Calculator();

    @Test
    void addsTwoPositiveNumbers() {
        assertEquals(5, calculator.add(2, 3));
    }

    @Test
    void subtractsToANegativeResult() {
        assertEquals(-4, calculator.subtract(3, 7));
    }

    @Test
    void dividesWithDecimalResult() {
        assertEquals(2.5, calculator.divide(5, 2));
    }

    @Test
    void divideByZeroThrowsException() {
        assertThrows(ArithmeticException.class, () -> calculator.divide(10, 0));
    }
}

How it works:

  • @Test (from org.junit.jupiter.api) marks a method as a test. JUnit finds and runs every such method.
  • assertEquals(expected, actual) passes when the two values are equal and fails the test otherwise. Put the expected value first; JUnit uses the order in its error message.
  • assertThrows passes only if the lambda throws the given exception type.
  • The class and its methods do not need to be public. Package-private is the usual JUnit style.
  • Method names describe the behaviour being checked, so a failing test name already tells you what broke.

Run JUnit Tests With Maven

Run all tests from the project folder:

mvn test

Output (shortened):

[INFO] -------------------------------------------------------
[INFO]  T E S T S
[INFO] -------------------------------------------------------
[INFO] Running com.gocourse.CalculatorTest
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.042 s -- in com.gocourse.CalculatorTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS

How it works:

  • mvn test compiles the main and test code, then Surefire runs every test class it finds.
  • Tests run: 4 matches the four @Test methods. All passed, so the build succeeds.

You can run a single class or a single method with the -Dtest option:

mvn test -Dtest=CalculatorTest
mvn test -Dtest=CalculatorTest#dividesWithDecimalResult

With Gradle, the equivalent commands are gradle test and gradle test --tests "com.gocourse.CalculatorTest". In IntelliJ IDEA, Eclipse or VS Code, click the green run icon next to a test class or method.

Note: By default, Surefire runs classes whose names end in Test, Tests or TestCase, or start with Test. A class named CalculatorChecks would be silently skipped.


Read a Failing Test Report

Tests are useful because they fail loudly. Suppose someone "optimizes" divide and accidentally uses integer division:

public double divide(int dividend, int divisor) {
    if (divisor == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    return dividend / divisor;   // bug: integer division, 5 / 2 == 2
}

Running mvn test again now reports the problem.

Output (shortened):

[ERROR] Tests run: 4, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.051 s <<< FAILURE! -- in com.gocourse.CalculatorTest
[ERROR] com.gocourse.CalculatorTest.dividesWithDecimalResult -- Time elapsed: 0.008 s <<< FAILURE!
org.opentest4j.AssertionFailedError: expected: <2.5> but was: <2.0>
	at com.gocourse.CalculatorTest.dividesWithDecimalResult(CalculatorTest.java:25)

[ERROR] Failures:
[ERROR]   CalculatorTest.dividesWithDecimalResult:25 expected: <2.5> but was: <2.0>
[ERROR] Tests run: 4, Failures: 1, Errors: 0, Skipped: 0
[INFO] BUILD FAILURE

How it works:

  • The report names the test method (dividesWithDecimalResult), the line (25), the expected value and the actual value.
  • AssertionFailedError comes from the opentest4j library that JUnit uses for failures.
  • Maven reports Failures for failed assertions and Errors for unexpected exceptions, such as a NullPointerException inside the code under test.
  • The build fails, so broken code cannot reach a release by accident.
ResultMeaning
PassedAll assertions in the test held
FailureAn assertion did not hold
ErrorThe test threw an exception that was not expected
SkippedThe test was disabled or an assumption was not met

Add Messages and Display Names

Two small additions make reports much easier to read. A message explains what was being checked, and @DisplayName gives a test a readable name in IDEs and reports.

package com.gocourse;

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

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

@DisplayName("Calculator")
class CalculatorMessagesTest {

    private final Calculator calculator = new Calculator();

    @Test
    @DisplayName("5 ÷ 2 gives 2.5, not 2")
    void divisionKeepsDecimals() {
        assertEquals(2.5, calculator.divide(5, 2), "divide() must not use integer division");
    }

    @Test
    @DisplayName("adding a negative number lowers the result")
    void addingNegativeNumber() {
        int result = calculator.add(10, -3);
        assertTrue(result < 10, () -> "Expected less than 10 but got " + result);
    }
}

With the integer-division bug still in place, the failure now reads:

divide() must not use integer division ==> expected: <2.5> but was: <2.0>

How it works:

  • The message is the last argument of an assertion. JUnit prints it before ==> when the assertion fails.
  • A Supplier<String> such as () -> "Expected ..." + result builds the message only if the test fails, which avoids extra work for passing tests.
  • @DisplayName can contain spaces, symbols and emoji. IDEs show 5 ÷ 2 gives 2.5, not 2 instead of divisionKeepsDecimals().

Run JUnit Without a Build Tool

For quick experiments you can run tests with the Console Launcher, a single JAR that contains the whole JUnit Platform. Download junit-platform-console-standalone-6.1.3.jar from Maven Central, then compile and run:

javac -d out -cp junit-platform-console-standalone-6.1.3.jar \
  src/main/java/com/gocourse/Calculator.java \
  src/test/java/com/gocourse/CalculatorTest.java

java -jar junit-platform-console-standalone-6.1.3.jar execute \
  --class-path out --scan-class-path

Output (shortened):

╷
├─ JUnit Jupiter ✔
│  └─ CalculatorTest ✔
│     ├─ addsTwoPositiveNumbers() ✔
│     ├─ subtractsToANegativeResult() ✔
│     ├─ dividesWithDecimalResult() ✔
│     └─ divideByZeroThrowsException() ✔
└─ JUnit Platform Suite ✔

Test run finished after 61 ms
[         4 tests found           ]
[         4 tests successful      ]
[         0 tests failed          ]

How it works:

  • javac compiles both the class and its test into out, with the standalone JAR on the classpath so the JUnit annotations resolve.
  • execute --scan-class-path finds every test class under out and runs it.
  • The tree view shows each engine, class and test method with a check mark or a cross. This is the same engine Maven, Gradle and IDEs use behind the scenes.

Real-World Example: Testing a Grade Calculator

A course platform turns marks into grades. The rules are easy to get wrong at the boundaries (is 90 an A or a B?), so this is exactly where tests help.

package com.gocourse;

import java.util.List;

public class GradeCalculator {

    public String gradeFor(int marks) {
        if (marks < 0 || marks > 100) {
            throw new IllegalArgumentException("Marks must be between 0 and 100, got " + marks);
        }
        if (marks >= 90) return "A";
        if (marks >= 75) return "B";
        if (marks >= 60) return "C";
        if (marks >= 40) return "D";
        return "F";
    }

    public double average(List<Integer> allMarks) {
        if (allMarks.isEmpty()) {
            throw new IllegalArgumentException("No marks to average");
        }
        return allMarks.stream().mapToInt(Integer::intValue).average().orElseThrow();
    }

    public boolean hasPassed(List<Integer> allMarks) {
        return average(allMarks) >= 40 && allMarks.stream().noneMatch(mark -> mark < 25);
    }
}

The test class checks normal values, exact boundaries and invalid input:

package com.gocourse;

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

import java.util.List;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("GradeCalculator")
class GradeCalculatorTest {

    private final GradeCalculator grades = new GradeCalculator();

    @Test
    @DisplayName("gives the right grade at every boundary")
    void gradeBoundaries() {
        assertEquals("A", grades.gradeFor(100));
        assertEquals("A", grades.gradeFor(90));
        assertEquals("B", grades.gradeFor(89));
        assertEquals("B", grades.gradeFor(75));
        assertEquals("C", grades.gradeFor(60));
        assertEquals("D", grades.gradeFor(40));
        assertEquals("F", grades.gradeFor(39));
        assertEquals("F", grades.gradeFor(0));
    }

    @Test
    @DisplayName("rejects marks outside 0 to 100")
    void rejectsInvalidMarks() {
        IllegalArgumentException error =
                assertThrows(IllegalArgumentException.class, () -> grades.gradeFor(101));
        assertEquals("Marks must be between 0 and 100, got 101", error.getMessage());
        assertThrows(IllegalArgumentException.class, () -> grades.gradeFor(-1));
    }

    @Test
    @DisplayName("averages a list of marks")
    void averagesMarks() {
        assertEquals(70.0, grades.average(List.of(60, 70, 80)));
    }

    @Test
    @DisplayName("refuses to average an empty list")
    void averageOfEmptyList() {
        assertThrows(IllegalArgumentException.class, () -> grades.average(List.of()));
    }

    @Test
    @DisplayName("passes a student with a good average and no very low mark")
    void studentPasses() {
        assertTrue(grades.hasPassed(List.of(55, 62, 48)));
    }

    @Test
    @DisplayName("fails a student with one mark below 25, even with a good average")
    void oneVeryLowMarkFails() {
        assertFalse(grades.hasPassed(List.of(95, 90, 20)), "a single mark below 25 must fail the student");
    }
}

Output of mvn test (shortened):

[INFO] Running com.gocourse.GradeCalculatorTest
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.037 s -- in com.gocourse.GradeCalculatorTest
[INFO]
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

How it works:

  1. Boundaries first. gradeBoundaries checks both sides of every grade limit (90 and 89, 40 and 39). Off-by-one mistakes such as writing > 90 instead of >= 90 are the most common bugs in rules like these, and this test catches them immediately.
  2. Invalid input. rejectsInvalidMarks checks that bad values throw IllegalArgumentException, and that the message is helpful. assertThrows returns the exception, so you can inspect it.
  3. One behaviour per test. Each method checks one rule and has a display name that reads like a requirement. When a test fails, its name tells you which rule broke.
  4. The tricky rule. oneVeryLowMarkFails documents a business rule that is easy to forget: an average of 68.3 is not enough if one mark is below 25. If someone later removes the noneMatch check, this test fails with the message given.

Each test also serves as documentation: a new team member can read GradeCalculatorTest to learn exactly how grading works.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java JUnit Basics and get answers drawn from it.

Signed-in readers only.