Testing and QA · Intermediate · 22 min
Write Java unit tests with JUnit 6 and AssertJ
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Eclipse Temurin JDK 25.0.5 · Maven 3.10.2 · JUnit 6.1.3 · AssertJ 3.27.7
You will test a small transfer-fee calculator with JUnit 6.1 and AssertJ 3.27, using display names, nested and parameterised tests, exception checks, soft assertions, a temporary folder and one Mockito mock, and finish with 18 passing tests from mvn test.
On this page
A unit test runs one small piece of your code in isolation and checks one behaviour. In Java, the standard tool for writing and running them is JUnit, and AssertJ is the assertion library many teams add on top because its checks read like sentences and its failure messages say exactly what differed.
In this tutorial you test a small calculator for mobile money transfer fees, the kind of percentage-with-a-floor-and-a-cap rule that payment apps in Kenya, Ghana, Nigeria and elsewhere apply to every transfer. You write the code first, then cover it with 18 tests that use the JUnit features you will meet most at work, and one Mockito mock for the part that would normally call a database.
If you already use JUnit 5, JUnit 6 will feel familiar: the annotations and the org.junit.jupiter packages are the same. The changes that affect you are these:
- Java 17 is the minimum. JUnit 6 no longer runs on Java 8 or 11.
- One version number. In JUnit 5, the Platform modules were numbered
1.xwhile Jupiter was5.x. In JUnit 6 every module, including the Platform, is6.1.3, so the BOM version and the artifact versions you see in a dependency tree all match. - Some old pieces are gone or going. The
junit-platform-runnermodule (running JUnit 5 tests through JUnit 4's@RunWith) has been removed, and the Vintage engine that runs JUnit 4 tests is deprecated. - CSV parsing changed underneath.
@CsvSourcenow uses the FastCSV library. Plain values like the ones in this tutorial behave as before; unusual quoting can be stricter.
Setting up a Maven project from nothing is covered in Build and test a Java project with Maven. This tutorial assumes Maven 3.10.2 and JDK 25 from that one.
Step 1 · Create the project and its pom.xml
Make a throwaway folder with Maven's standard layout, one tree for code and one for tests:
mkdir -p ~/junit-demo/transfer-fees
cd ~/junit-demo/transfer-fees
mkdir -p src/main/java/com/example/fees src/test/java/com/example/feesNow write the pom.xml. Three test libraries go in, all with test scope so none of them ships with your app:
junit-jupiter, with its version taken from the JUnit 6.1.3 BOM. It brings the API you write tests against, parameterised tests and the engine that runs them.assertj-core3.27.7 for assertions.mockito-core5.24.0 for the one mock.
The <plugins> section does one job for Mockito. Since Java 21, the JDK warns when a library attaches a Java agent to its own running JVM, and Mockito relies on one to create mocks. The fix is to start the test JVM with Mockito as an agent: the dependency plugin's properties goal puts the path of the Mockito JAR in a property named org.mockito:mockito-core:jar, and Surefire, the plugin that runs tests, passes it to -javaagent. The statelessTestsetReporter block changes one thing in Surefire's XML reports: by default each testcase is named after the Java method, and with usePhrasedTestCaseMethodName it uses the readable @DisplayName text instead, which is what CI servers then show. Every other plugin version is pinned, which Maven 3.10 expects.
cat > pom.xml <<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>transfer-fees</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>25</maven.compiler.release>
<junit.version>6.1.3</junit.version>
<assertj.version>3.27.7</assertj.version>
<mockito.version>5.24.0</mockito.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>${junit.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>${mockito.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.5.0</version>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.5.0</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.16.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.5.1</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.11.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>locate-mockito-agent</id>
<goals>
<goal>properties</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-javaagent:${org.mockito:mockito-core:jar}</argLine>
<statelessTestsetReporter implementation="org.apache.maven.plugin.surefire.extensions.junit5.JUnit5Xml30StatelessReporter">
<usePhrasedTestCaseMethodName>true</usePhrasedTestCaseMethodName>
</statelessTestsetReporter>
</configuration>
</plugin>
</plugins>
</build>
</project>
XML
mvn validateThe first run downloads plugins into ~/.m2/repository, and the first mvn test later fetches the three libraries, a few megabytes in all. On prepaid mobile data, do this part on Wi-Fi if you can; after that, mvn -o test works offline.
Check it worked
mvn validate ends with BUILD SUCCESS. If it reports a duplicated dependency or an unresolvable version, compare that block with the one above character by character.
Step 2 · Write the code under test
The fee rule: a provider charges a rate in basis points (150 basis points is 1.5%), rounded up to the next minor unit (kobo, cent, pesewa), never less than 10.00 and never more than 5,000.00. Amounts are whole minor units in a long, so there is no double rounding to worry about.
Four small files. Transfer is a record that refuses nonsense input:
cat > src/main/java/com/example/fees/Transfer.java <<'JAVA'
package com.example.fees;
import java.util.Objects;
public record Transfer(String provider, long amountMinor) {
public Transfer {
Objects.requireNonNull(provider, "provider");
if (provider.isBlank()) {
throw new IllegalArgumentException("provider is blank");
}
if (amountMinor <= 0) {
throw new IllegalArgumentException("amount must be positive, was " + amountMinor);
}
}
}
JAVATariffSource is the collaborator. In a real app it would read rates from a database or a pricing service; in tests you replace it:
cat > src/main/java/com/example/fees/TariffSource.java <<'JAVA'
package com.example.fees;
@FunctionalInterface
public interface TariffSource {
/** The provider's fee in basis points: 150 means 1.5%. */
int basisPoints(String provider);
}
JAVAFeeCalculator holds the rule. Math.clamp keeps the result between the floor and the cap:
cat > src/main/java/com/example/fees/FeeCalculator.java <<'JAVA'
package com.example.fees;
public final class FeeCalculator {
public static final long MIN_FEE = 1_000;
public static final long MAX_FEE = 500_000;
private final TariffSource tariffs;
public FeeCalculator(TariffSource tariffs) {
this.tariffs = tariffs;
}
public long feeFor(Transfer transfer) {
int basisPoints = tariffs.basisPoints(transfer.provider());
if (basisPoints < 0) {
throw new IllegalStateException("negative tariff for " + transfer.provider());
}
long raw = (transfer.amountMinor() * basisPoints + 9_999) / 10_000;
return Math.clamp(raw, MIN_FEE, MAX_FEE);
}
}
JAVAReceiptWriter saves a plain-text receipt into a folder you choose:
cat > src/main/java/com/example/fees/ReceiptWriter.java <<'JAVA'
package com.example.fees;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Locale;
public final class ReceiptWriter {
private ReceiptWriter() {
}
public static Path write(Path folder, Transfer transfer, long feeMinor) throws IOException {
Path file = folder.resolve("receipt-" + transfer.provider() + ".txt");
List<String> lines = List.of(
"provider: " + transfer.provider(),
"amount: " + format(transfer.amountMinor()),
"fee: " + format(feeMinor),
"total: " + format(transfer.amountMinor() + feeMinor));
return Files.write(file, lines, StandardCharsets.UTF_8);
}
static String format(long minorUnits) {
return String.format(Locale.ROOT, "%d.%02d", minorUnits / 100, minorUnits % 100);
}
}
JAVA
mvn compileCheck it worked
mvn compile ends with BUILD SUCCESS and target/classes/com/example/fees/ now holds four .class files. A compile error names the file and line; the usual cause is a missing line from a copy.
Step 3 · Write your first tests with @Test, @DisplayName and assertThrows
Test classes live in the same package as the code, under src/test/java, and by Surefire's default their names end in Test. Each test is a method marked @Test. Neither the class nor the methods need to be public in JUnit 5 or 6.
This class shows JUnit's own assertThrows next to AssertJ's assertThatThrownBy, so you can compare them:
cat > src/test/java/com/example/fees/TransferTest.java <<'JAVA'
package com.example.fees;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
@DisplayName("A transfer")
class TransferTest {
@Test
@DisplayName("keeps its provider and amount")
void keepsValues() {
Transfer transfer = new Transfer("acme", 250_000);
assertThat(transfer.provider()).isEqualTo("acme");
assertThat(transfer.amountMinor()).isPositive().isEqualTo(250_000);
}
@Test
@DisplayName("rejects a zero amount")
void rejectsZero() {
IllegalArgumentException error =
assertThrows(IllegalArgumentException.class, () -> new Transfer("acme", 0));
assertThat(error).hasMessage("amount must be positive, was 0");
}
@Test
@DisplayName("rejects a blank provider")
void rejectsBlankProvider() {
assertThatThrownBy(() -> new Transfer(" ", 5_000))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("blank");
}
}
JAVA
mvn testA few things to notice:
@DisplayNamegives a test a readable name. Your IDE's test runner shows "rejects a zero amount" under "A transfer" rather thanrejectsZero, and, because of the reporter setting in thepom.xml, so does Surefire's XML report. Without that setting the report would use the method name. The method name still matters for searching code, so keep both clear.- Import assertions statically from one place per library. Mixing
org.junit.jupiter.api.Assertions.assertEqualsand AssertJ in one file works, but a team should agree on one style; this tutorial uses AssertJ everywhere except to showassertThrows. - AssertJ chains checks:
isPositive().isEqualTo(250_000)stops at the first that fails and names it.
Check it worked
The output has a line like Tests run: 3, Failures: 0, Errors: 0, Skipped: 0 for com.example.fees.TransferTest, then BUILD SUCCESS. To see a failure message, change "acme" to "other" in the first isEqualTo, run mvn test again and read the expected: and but was: lines, then change it back.
Step 4 · Replace the collaborator with a Mockito mock and group tests with @Nested
FeeCalculator needs a TariffSource. A mock is a stand-in object you program for the test: when asked for "acme", return 150. You can then also check how the calculator used it.
@BeforeEach runs before every test, so each one gets a fresh mock. @Nested inner classes group related tests under their own display name, and they share the outer class's fields and setup:
cat > src/test/java/com/example/fees/FeeCalculatorTest.java <<'JAVA'
package com.example.fees;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
@DisplayName("The fee calculator")
class FeeCalculatorTest {
private TariffSource tariffs;
private FeeCalculator calculator;
@BeforeEach
void setUp() {
tariffs = mock(TariffSource.class);
when(tariffs.basisPoints("acme")).thenReturn(150);
calculator = new FeeCalculator(tariffs);
}
@Test
@DisplayName("asks for the tariff of the transfer's provider, once")
void asksForProvider() {
calculator.feeFor(new Transfer("acme", 100_000));
verify(tariffs).basisPoints("acme");
verifyNoMoreInteractions(tariffs);
}
@Test
@DisplayName("refuses a negative tariff")
void refusesNegativeTariff() {
when(tariffs.basisPoints("broken")).thenReturn(-5);
assertThatThrownBy(() -> calculator.feeFor(new Transfer("broken", 100_000)))
.isInstanceOf(IllegalStateException.class)
.hasMessage("negative tariff for broken");
}
@Nested
@DisplayName("for small transfers")
class SmallTransfers {
@Test
@DisplayName("charges the minimum fee")
void chargesMinimum() {
assertThat(calculator.feeFor(new Transfer("acme", 50_000))).isEqualTo(FeeCalculator.MIN_FEE);
}
}
@Nested
@DisplayName("for large transfers")
class LargeTransfers {
@Test
@DisplayName("caps the fee at the maximum")
void capsFee() {
assertThat(calculator.feeFor(new Transfer("acme", 40_000_000))).isEqualTo(FeeCalculator.MAX_FEE);
}
}
}
JAVA
mvn testUse a mock for one reason here: the real TariffSource would be slow or need a database. Do not mock the code you are testing, and do not mock simple values such as Transfer; create real ones. If you find yourself writing many when(...) lines for one test, that is usually a sign the class does too much.
Because the agent is attached at JVM start, you should not see Mockito's warning about dynamically loading an agent. You may still see a one-line JVM warning that class sharing is limited because the bootstrap classpath was appended; it does not affect the results.
Check it worked
Seven tests pass in total. Surefire reports the nested classes on their own lines, named something like FeeCalculatorTest$SmallTransfers. To watch verifyNoMoreInteractions catch a problem, add the line tariffs.basisPoints("other"); inside feeFor, run mvn test and find the failure for asksForProvider: verify(tariffs).basisPoints("acme") still passes, so verifyNoMoreInteractions reports No interactions wanted here and lists the unexpected basisPoints("other") call. Other tests fail too while the line is there. Remove it and run again.
Step 5 · Cover the fee table with @ParameterizedTest
The fee rule has edges: the floor, rounding up, the plain percentage and the cap. Writing one test method per amount repeats itself. A parameterised test runs one method once per row of data.
Two sources are common. @CsvSource takes inline comma-separated rows, and JUnit converts each column to the parameter's type. @MethodSource names a static method that returns the rows, useful when a row needs objects or is too long for a string.
This class also shows another way to replace a collaborator: TariffSource has one method, so a lambda can stand in for it. That is a stub, a fixed answer with nothing to verify, and it is all these tests need:
cat > src/test/java/com/example/fees/FeeTableTest.java <<'JAVA'
package com.example.fees;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.MethodSource;
@DisplayName("The fee table")
class FeeTableTest {
private static final Map<String, Integer> TARIFFS =
Map.of("acme", 150, "north", 100, "south", 250, "promo", 0);
private final FeeCalculator calculator = new FeeCalculator(TARIFFS::get);
@ParameterizedTest(name = "acme: {0} minor units costs {1}")
@CsvSource({
"50000, 1000", // 7.50 is below the 10.00 floor
"66667, 1001", // 10.00005 rounds up
"100000, 1500", // exactly 1.5%
"1000000, 15000",
"40000000, 500000" // 6,000.00 is above the 5,000.00 cap
})
void feeForAmount(long amountMinor, long expectedFee) {
assertThat(calculator.feeFor(new Transfer("acme", amountMinor))).isEqualTo(expectedFee);
}
static Stream<Arguments> providers() {
return Stream.of(
Arguments.of("acme", 3_000L),
Arguments.of("north", 2_000L),
Arguments.of("south", 5_000L),
Arguments.of("promo", FeeCalculator.MIN_FEE));
}
@ParameterizedTest(name = "{0} charges {1} on 2,000.00")
@MethodSource("providers")
void feeForProvider(String provider, long expectedFee) {
assertThat(calculator.feeFor(new Transfer(provider, 200_000))).isEqualTo(expectedFee);
}
}
JAVA
mvn testThe name attribute controls how each run is labelled, with {0} and {1} replaced by the row's values. The comments after each CSV row are Java comments outside the strings, so JUnit never sees them; they tell the next reader why each row is there. Choosing rows at the edges (just below the floor, just above it, at the cap) is what makes a table like this worth having.
Check it worked
The FeeTableTest line reports Tests run: 9: five CSV rows and four providers, each counted as its own test. Open target/surefire-reports/TEST-com.example.fees.FeeTableTest.xml and you will find a testcase whose name is the method signature followed by the display name, feeForAmount(long, long) acme: "66667" minor units costs "1001", with each quote written as " in the XML. JUnit 6 puts text values in quotes when it fills in {0} and {1}, and every @CsvSource column starts out as text; the long values from providers() stay unquoted, so that test reads "acme" charges 3000 on 2,000.00. Without the reporter setting it would be something like feeForAmount(long, long)[2]. The run total is now 16.
Step 6 · Test file output with @TempDir and soft assertions
Code that writes files needs somewhere safe to write. A parameter marked @TempDir gets a fresh, empty folder that JUnit creates before the test and deletes afterwards, so tests never touch your home folder or each other's files.
The second test uses soft assertions. Normal assertions stop at the first failure. SoftAssertions.assertSoftly runs every check in the block, then reports all the failures together, which helps when one test checks several independent values:
cat > src/test/java/com/example/fees/ReceiptWriterTest.java <<'JAVA'
package com.example.fees;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
@DisplayName("The receipt writer")
class ReceiptWriterTest {
@Test
@DisplayName("writes one line per field into the folder it is given")
void writesReceipt(@TempDir Path folder) throws IOException {
Path file = ReceiptWriter.write(folder, new Transfer("acme", 250_000), 3_750);
assertThat(file).exists().hasFileName("receipt-acme.txt").hasParentRaw(folder);
assertThat(Files.readAllLines(file, StandardCharsets.UTF_8)).containsExactly(
"provider: acme",
"amount: 2500.00",
"fee: 37.50",
"total: 2537.50");
}
@Test
@DisplayName("formats minor units with two decimal places")
void formatsAmounts() {
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(ReceiptWriter.format(5)).isEqualTo("0.05");
softly.assertThat(ReceiptWriter.format(100)).isEqualTo("1.00");
softly.assertThat(ReceiptWriter.format(123_456)).isEqualTo("1234.56");
});
}
}
JAVA
mvn testcontainsExactly checks both the lines and their order, and on failure prints which lines were missing or unexpected. Reading lines back, rather than comparing the whole file as one string, also keeps the test working on Windows, where Files.write ends lines with \r\n.
Check it worked
All 18 tests pass. Run ls /tmp (or your system's temporary folder) before and after mvn test: no junit folder is left behind, because JUnit deletes the temporary folder when each test ends.
Step 7 · Read a soft assertion failure
Seeing the report once makes it easy to recognise later. Create a throwaway test with two wrong expectations:
cat > src/test/java/com/example/fees/SoftDemoTest.java <<'JAVA'
package com.example.fees;
import org.assertj.core.api.SoftAssertions;
import org.junit.jupiter.api.Test;
class SoftDemoTest {
@Test
void reportsEveryFailure() {
SoftAssertions.assertSoftly(softly -> {
softly.assertThat(ReceiptWriter.format(5)).isEqualTo("0.5");
softly.assertThat(ReceiptWriter.format(100)).isEqualTo("1.00");
softly.assertThat(ReceiptWriter.format(250)).isEqualTo("2.5");
});
}
}
JAVARun only that class. -Dtest takes a class name, and the build fails, as it should:
mvn test -Dtest=SoftDemoTestNow delete it, so it never reaches your repository:
rm src/test/java/com/example/fees/SoftDemoTest.javaCheck it worked
Before you deleted the file, the run ended with BUILD FAILURE and a report that starts Multiple Failures (2 failures), followed by -- failure 1 -- with the lines expected: "0.5" and but was: "0.05", and -- failure 2 -- with expected: "2.5" and but was: "2.50". The middle check passed, so it is not listed. With ordinary assertThat calls you would have seen only the first failure. ls src/test/java/com/example/fees now lists four test files.
Step 8 · Run the whole suite from a clean build
Run the suite as your continuous integration would, from nothing, so no stale compiled classes or old reports can hide a problem:
mvn clean test
ls target/surefire-reportsSurefire writes two files per test class: a .txt summary and an XML report that CI servers such as GitHub Actions or Jenkins read to show results. When a test fails in CI, these files are where you look first.
When you have finished, remove the demo folder with rm -rf ~/junit-demo. The libraries stay cached in ~/.m2/repository for your next project.
Check it worked
The run ends with Tests run: 18, Failures: 0, Errors: 0, Skipped: 0 and BUILD SUCCESS. The report folder lists files for TransferTest, FeeCalculatorTest and its two nested classes, FeeTableTest and ReceiptWriterTest, and nothing for SoftDemoTest.
Next steps
- If you skipped the project set-up, Build and test a Java project with Maven explains every part of the
pom.xml, the lifecycle phases and the Maven wrapper. - Write unit tests that stay useful covers naming, what to assert and how to keep a suite from breaking on every refactor.
- Choose between mocks, stubs and fakes goes further into the Mockito mock and the lambda stub you used here.
- Choose what to test with the test pyramid shows where unit tests fit alongside integration and end-to-end tests.
Related tutorials
- Write unit tests that stay useful as the code changesYou will replace a brittle pytest suite with behaviour tests that catch a real boundary bug and stay green when the code under them is rewritten.
- Write property-based tests in TypeScript with fast-checkYou will use fast-check and Vitest to find a rounding bug in a TypeScript money module, replay the failure from its seed, fix it, and model-test a shopping cart with generated command sequences.
- Write negative tests for an API: bad input, auth and limitsYou will build a pytest and httpx suite that attacks a small FastAPI ordering API with missing and extra fields, wrong types, boundary values, long and multilingual text, bad tokens, another user's data, rate limits and reused idempotency keys, and proves every error comes back in one RFC 9457 format.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials