Lesson 20 of 23

In progress

Course progress

Java

Testing with JUnit

Write a first JUnit test, name cases after the rule they check, and use parameterised tests and assertions that explain failures.

A test is a method that checks one behaviour and fails loudly when it changes. JUnit gives it a runner, assertions and a report, which is all most Java projects need.

What you will learn

  • Write @Test methods with meaningful assertions.
  • Structure tests with setup and clear names.
  • Use parameterised tests for tables of cases.

The first test

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PriceTest {
@Test
void addsTaxRoundedToTheNearestPaise() {
long result = Prices.withTax(45_000L);
assertEquals(53_100L, result);
}
}

The method is package-private and returns void. @Test marks it, and assertEquals(expected, actual) fails with both values in the message.

The name states the rule, not the method: addsTaxRoundedToTheNearestPaise tells a reader what the class promises. A test called testWithTax documents nothing and, when it fails, says nothing about what broke.

Assertions

assertEquals(4, 2 + 2);
assertTrue(list.isEmpty());
assertFalse(list.contains("x"));
assertNull(value);
assertNotNull(value);
assertThrows(IllegalArgumentException.class, () -> Prices.withTax(-1));

assertEquals compares with equals for objects and == for primitives. For arrays, use assertArrayEquals; for doubles, pass a delta: assertEquals(3.14, value, 0.001).

assertThrows both checks the type and lets you inspect the exception:

var error = assertThrows(IllegalArgumentException.class,
() -> Prices.withTax(-1));
assertTrue(error.getMessage().contains("negative"));

That covers the message without pinning its exact wording, which would break on every copy edit.

Arrange, act, assert

@Test
void removesOnlyMatchingItems() {
// arrange
Basket basket = new Basket();
basket.add(1_000L);
basket.add(2_000L);
// act
basket.remove(1_000L);
// assert
assertEquals(2_000L, basket.totalPaise());
assertEquals(1, basket.size());
}

The three sections make the test scannable: what exists, what happened, what should be true. When a test grows beyond one screen, it is usually testing several behaviours and should be split.

Setup and teardown

import org.junit.jupiter.api.BeforeEach;
class BasketTest {
private Basket basket;
@BeforeEach
void setUp() {
basket = new Basket();
basket.add(1_000L);
}
@Test
void totalsAddedItems() {
basket.add(500L);
assertEquals(1_500L, basket.totalPaise());
}
}

@BeforeEach runs before every test, so each starts from the same state and one test cannot affect another. @AfterEach cleans up external resources; most tests need neither.

Static state is the usual reason tests interfere: a static counter incremented by one test changes what the next sees. Avoid mutable static fields in production code and the problem disappears.

Parameterised tests

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class SlugTest {
@ParameterizedTest
@CsvSource({
"Hello World, hello-world",
"'  Spaced  ', spaced",
"'A  B', a-b",
"'Hello, World!', hello-world"
})
void turnsTextIntoASlug(String input, String expected) {
assertEquals(expected, Slugs.slug(input));
}
}

One test, four cases, and a failure names the row that failed. That is the cheapest way to cover boundaries and previously broken inputs.

@ValueSource supplies single values, @MethodSource a method returning arguments, and @EnumSource every constant of an enum.

What to test

  • The rules the class promises.
  • Boundaries: zero, one, the maximum, an empty collection.
  • Every bug you have fixed, as a regression test.

A test that is hard to write usually points at a design problem: a dependency created inside the method, or a method doing two things at once. Fixing the test often fixes the design.

Do not test getters, third-party libraries, or private methods directly. A private method that needs its own test is usually a class waiting to be extracted.

Test doubles

A dependency such as a repository or an HTTP client makes a test slow and flaky. Replace it with a small implementation or a mock.

interface Clock { java.time.Instant now(); }
class FixedClock implements Clock {
private final java.time.Instant instant;
FixedClock(String iso) { this.instant = java.time.Instant.parse(iso); }
public java.time.Instant now() { return instant; }
}

Injecting a Clock instead of calling Instant.now() directly makes time-dependent code testable without a library. That design change is often worth more than the mocking framework it replaces.

Mocks are appropriate when the interaction itself is the contract, such as "this method must be called once". They become a problem when a test asserts on five internal calls, which locks in an implementation rather than a behaviour.

Running

mvn test
gradle test

Both discover src/test/java, run the methods and report failures with the assertion message and the stack trace. In an IDE, a green bar next to the test method runs just that one, which is the loop you will use most.

Writing a test that catches every exception and passes. try { ... } catch (Exception e) { } with no assertion succeeds even when the code is broken; let the failure propagate, or use assertThrows.

Write tests for a clamp(value, min, max) method: a normal value, a value below the minimum, a value above the maximum, and the case where min equals max.

Show solution
import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ClampTest { @Test void keepsValuesInsideTheRange() { assertEquals(5, Numbers.clamp(5, 0, 10)); } @Test void raisesValuesBelowTheMinimum() { assertEquals(0, Numbers.clamp(-3, 0, 10)); } @Test void lowersValuesAboveTheMaximum() { assertEquals(10, Numbers.clamp(99, 0, 10)); } @Test void handlesAnEmptyRange() { assertEquals(4, Numbers.clamp(7, 4, 4)); } }

Four small tests, each naming one rule. When one fails, the name says which rule broke, and the empty-range case documents behaviour that a reader would otherwise have to infer from the implementation.

Recap

  • @Test methods check one behaviour and fail with a message that includes the values.
  • Name tests after the rule, and structure them as arrange, act, assert.
  • Parameterised tests cover tables of cases; inject dependencies to make code testable.

Next, streams: describing a pipeline over a collection instead of writing loops.

JUnit 4 or 5?
JUnit 5 for new code. JUnit 4 tests still run in most projects, and the annotations differ.
How much coverage is enough?
Enough to cover the rules and the bugs. A percentage is a rough signal, not a target to game.

Progress is saved in this browser only. No account, no email.

Admin

About the author

Admin

Instructor and technical writer at tutorials.in

Writes beginner lessons for tutorials.in. Each lesson is checked against the language or tool documentation, and examples are run before publishing.

Reviewed by the editorial team before publishing. Last updated November 16, 2026.