Java JUnit Basics
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 checking | JUnit testing |
|---|---|
Run main, read the console | Run all tests with one command |
| You remember what "correct" looks like | The expected value is written in the test |
| Slow to repeat, easy to skip | Runs on every build, in seconds |
| A broken feature may go unnoticed | A failing test names the exact method and value |
JUnit 6 is made of three parts:
| Module | What it does |
|---|---|
| JUnit Platform | Launches tests and reports results; used by Maven, Gradle and IDEs |
| JUnit Jupiter | The API you write tests with: @Test, Assertions, @BeforeEach and more |
| JUnit Vintage | Runs 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 stillorg.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-jupiteris 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 undersrc/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'stesttask 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(fromorg.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.assertThrowspasses 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 testcompiles the main and test code, then Surefire runs every test class it finds.Tests run: 4matches the four@Testmethods. 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,TestsorTestCase, or start withTest. A class namedCalculatorCheckswould 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. AssertionFailedErrorcomes from theopentest4jlibrary that JUnit uses for failures.- Maven reports Failures for failed assertions and Errors for unexpected exceptions, such as a
NullPointerExceptioninside the code under test. - The build fails, so broken code cannot reach a release by accident.
| Result | Meaning |
|---|---|
| Passed | All assertions in the test held |
| Failure | An assertion did not hold |
| Error | The test threw an exception that was not expected |
| Skipped | The 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 ..." + resultbuilds the message only if the test fails, which avoids extra work for passing tests. @DisplayNamecan contain spaces, symbols and emoji. IDEs show5 ÷ 2 gives 2.5, not 2instead ofdivisionKeepsDecimals().
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:
javaccompiles both the class and its test intoout, with the standalone JAR on the classpath so the JUnit annotations resolve.execute --scan-class-pathfinds every test class underoutand 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:
- Boundaries first.
gradeBoundarieschecks both sides of every grade limit (90 and 89, 40 and 39). Off-by-one mistakes such as writing> 90instead of>= 90are the most common bugs in rules like these, and this test catches them immediately. - Invalid input.
rejectsInvalidMarkschecks that bad values throwIllegalArgumentException, and that the message is helpful.assertThrowsreturns the exception, so you can inspect it. - 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.
- The tricky rule.
oneVeryLowMarkFailsdocuments 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 thenoneMatchcheck, 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.