Testing with JUnit 5
Course contents (20 lessons)
- Getting started
- Installing JDK 21 and running Java code
- Your first program: how a Java file is built
- Language basics
- Variables and data types
- Strings, formatting and text blocks
- Control flow: if, switch expressions and loops
- Data and methods
- Arrays and the collections framework
- Methods, overloading and varargs
- Object-oriented Java
- Classes, objects and encapsulation
- Inheritance, abstract classes and interfaces
- Records, enums and sealed types
- Writing robust code
- Exceptions: checked, unchecked and try-with-resources
- Generics, bounded types and wildcards
- Files and the NIO.2 API
- Modern Java
- Lambdas and the Stream API
- Optional: handling missing values
- Concurrency: executors, CompletableFuture and virtual threads
- Tools, services and the final project
- Maven and Gradle basics
- Testing with JUnit 5
- A small REST service with the JDK HTTP server
- Final project: a library manager
What a test gives you
A unit test is a small program that calls your code and checks the result. You run all of them with one command, in seconds, and you learn straight away when a change broke something. Over time the tests also describe what the code is supposed to do, in a way that does not go out of date.
JUnit 5 is the standard testing framework for Java. Add it to your build as shown in the previous lesson, and put test classes under src/test/java. Run them with mvn test or ./gradlew test, or from the test runner in your IDE.
A first set of tests
Here is a class that calculates the price of an order, and its test class. They are shown in one listing to make them easy to read. In a project, they are two files: PriceCalculator.java in src/main/java and PriceCalculatorTest.java in src/test/java, both in the same package.
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class PriceCalculator {
private final Supplier<LocalDate> today;
PriceCalculator(Supplier<LocalDate> today) {
this.today = today;
}
BigDecimal total(BigDecimal unitPrice, int quantity) {
if (unitPrice.signum() < 0) {
throw new IllegalArgumentException("unitPrice must not be negative");
}
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
BigDecimal total = unitPrice.multiply(BigDecimal.valueOf(quantity));
if (quantity >= 10) {
total = total.multiply(new BigDecimal("0.90")); // bulk discount
}
if (today.get().getDayOfWeek() == DayOfWeek.FRIDAY) {
total = total.multiply(new BigDecimal("0.98")); // Friday offer
}
return total.setScale(2, java.math.RoundingMode.HALF_UP);
}
}
class PriceCalculatorTest {
private static final LocalDate MONDAY = LocalDate.of(2026, 3, 2);
private static final LocalDate FRIDAY = LocalDate.of(2026, 3, 6);
private PriceCalculator calculator;
@BeforeEach
void setUp() {
calculator = new PriceCalculator(() -> MONDAY); // a fixed "today"
}
@Test
@DisplayName("multiplies unit price by quantity")
void multipliesPriceByQuantity() {
BigDecimal result = calculator.total(new BigDecimal("250"), 4);
assertEquals(new BigDecimal("1000.00"), result);
}
@ParameterizedTest(name = "{0} items cost {1}")
@CsvSource({
"9, 900.00",
"10, 900.00",
"20, 1800.00"
})
void appliesBulkDiscountFromTenItems(int quantity, String expected) {
BigDecimal result = calculator.total(new BigDecimal("100"), quantity);
assertEquals(new BigDecimal(expected), result);
}
@Test
void appliesFridayOffer() {
PriceCalculator friday = new PriceCalculator(() -> FRIDAY);
assertEquals(new BigDecimal("98.00"), friday.total(new BigDecimal("100"), 1));
}
@ParameterizedTest
@ValueSource(ints = {0, -1, -50})
void rejectsNonPositiveQuantity(int quantity) {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
() -> calculator.total(BigDecimal.TEN, quantity));
assertTrue(ex.getMessage().contains("quantity"));
}
@Test
void checksSeveralThingsAtOnce() {
BigDecimal result = calculator.total(new BigDecimal("10"), 3);
assertAll(
() -> assertEquals(2, result.scale()),
() -> assertTrue(result.compareTo(BigDecimal.ZERO) > 0),
() -> assertEquals(new BigDecimal("30.00"), result)
);
}
}
Walking through it
The calculator takes a Supplier<LocalDate> instead of calling LocalDate.now() itself. In production you pass LocalDate::now. In tests you pass a lambda that returns a fixed date. This is dependency injection by hand, with no framework. It means the Friday rule can be tested on any day of the week. A test that depends on the clock, on random numbers or on the network will fail at some point for no reason, and teams stop trusting tests like that. Java also has java.time.Clock, which is the standard way to do the same thing.
A test method is marked with @Test. It needs no public modifier in JUnit 5, and it returns void. Each test follows the same pattern, often called Arrange, Act, Assert: create the objects, call the method, check the outcome. @BeforeEach runs before every test, and it creates a fresh calculator. JUnit also creates a new instance of the test class for every test method, so tests cannot affect each other through fields.
The assertions come from Assertions. Note the argument order: assertEquals(expected, actual). If you swap them, the failure message is misleading. Be careful when you compare BigDecimal: equals considers the scale, so 1000.00 and 1000 are different. That is why the calculator sets the scale and why the tests use two decimals. assertThrows checks that the code throws the given exception type, and returns it so you can inspect the message.
The parameterised tests run one method several times with different data. @CsvSource supplies rows, and JUnit converts the strings to the parameter types. @ValueSource gives a list of single values. The name pattern in @ParameterizedTest makes the report readable, as in "9 items cost 900.00". The bulk discount cases cover the boundary: nine items get no discount, ten do. Bugs gather at boundaries, so test one below, on and above.
assertAll runs every assertion and reports all failures, instead of stopping at the first one.
What to test
- Business rules, calculations and edge cases. That is where the value is.
- Error handling: does the code reject bad input with a clear exception?
- Not the framework or the language. You do not need a test that proves
ArrayList.addworks. - Not private methods directly. Test them through the public ones. If a private method is complex enough to need its own tests, it probably deserves its own class.
When the code under test talks to a database or a web service, hide it behind an interface and use a simple fake class in the test. Libraries such as Mockito can create fakes automatically, but a hand-written fake is often easier to read.
Common mistakes
- Tests that depend on time, order or shared state.
- Swapped expected and actual values.
- One giant test method that checks ten things. When it fails, you do not know which one is broken.
- Never seeing a test fail. Break the code on purpose once to be sure the test notices.
- Mixing JUnit 4 and 5 imports. JUnit 5 uses
org.junit.jupiter.api. Theorg.junit.Testannotation is the old one, and it will not run.
Try it yourself
- Set up the project from the previous lesson and add these two files. Run
mvn test. - Add a rule that orders over 5000 get free shipping of 250, write the failing test first and then the code.
- Add a parameterised test with
@MethodSourcethat feeds in a list ofArguments.
import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.util.function.Supplier;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
class PriceCalculator {
private final Supplier<LocalDate> today;
PriceCalculator(Supplier<LocalDate> today) {
this.today = today;
}
BigDecimal total(BigDecimal unitPrice, int quantity) {
if (unitPrice.signum() < 0) {
throw new IllegalArgumentException("unitPrice must not be negative");
}
if (quantity <= 0) {
throw new IllegalArgumentException("quantity must be positive");
}
BigDecimal total = unitPrice.multiply(BigDecimal.valueOf(quantity));
if (quantity >= 10) {
total = total.multiply(new BigDecimal("0.90")); // bulk discount
}
if (today.get().getDayOfWeek() == DayOfWeek.FRIDAY) {
total = total.multiply(new BigDecimal("0.98")); // Friday offer
}
return total.setScale(2, java.math.RoundingMode.HALF_UP);
}
}
class PriceCalculatorTest {
private static final LocalDate MONDAY = LocalDate.of(2026, 3, 2);
private static final LocalDate FRIDAY = LocalDate.of(2026, 3, 6);
private PriceCalculator calculator;
@BeforeEach
void setUp() {
calculator = new PriceCalculator(() -> MONDAY); // a fixed "today"
}
@Test
@DisplayName("multiplies unit price by quantity")
void multipliesPriceByQuantity() {
BigDecimal result = calculator.total(new BigDecimal("250"), 4);
assertEquals(new BigDecimal("1000.00"), result);
}
@ParameterizedTest(name = "{0} items cost {1}")
@CsvSource({
"9, 900.00",
"10, 900.00",
"20, 1800.00"
})
void appliesBulkDiscountFromTenItems(int quantity, String expected) {
BigDecimal result = calculator.total(new BigDecimal("100"), quantity);
assertEquals(new BigDecimal(expected), result);
}
@Test
void appliesFridayOffer() {
PriceCalculator friday = new PriceCalculator(() -> FRIDAY);
assertEquals(new BigDecimal("98.00"), friday.total(new BigDecimal("100"), 1));
}
@ParameterizedTest
@ValueSource(ints = {0, -1, -50})
void rejectsNonPositiveQuantity(int quantity) {
IllegalArgumentException ex = assertThrows(IllegalArgumentException.class,
() -> calculator.total(BigDecimal.TEN, quantity));
assertTrue(ex.getMessage().contains("quantity"));
}
@Test
void checksSeveralThingsAtOnce() {
BigDecimal result = calculator.total(new BigDecimal("10"), 3);
assertAll(
() -> assertEquals(2, result.scale()),
() -> assertTrue(result.compareTo(BigDecimal.ZERO) > 0),
() -> assertEquals(new BigDecimal("30.00"), result)
);
}
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account