Sub topic 11
Grouping Tests with @Nested
As a test class grows, it can turn into a long, flat list of methods. Some tests check a brand-new object. Others check the same object after something has happened to it. When all of them sit side by side, it is hard to see which tests belong together.
JUnit 5 lets you group related tests inside a test class. You do this with nested test classes. A nested test class is a class written inside another test class and marked with the @Nested annotation. Each group can have its own name and its own setup code.
This chapter shows how to write nested tests, how their setup runs, and the mistakes beginners make most often.
Why Group Tests?
Most objects behave differently depending on their state, meaning the data they hold right now. An empty bank account and a bank account with money in it are both bank accounts, but they react differently when you try to take money out.
Nested classes let you organize tests by state:
- One group for "a new account".
- One group for "an account after a deposit".
- A deeper group for "an account after a deposit and a full withdrawal".
Each group sets up its own starting state once, in a @BeforeEach method. The tests inside the group then only need to do the Act and Assert steps.
The Code Under Test
All examples in this chapter test this small class:
public class BankAccount {
private int balance;
public int getBalance() {
return balance;
}
public void deposit(int amount) {
if (amount <= 0) {
throw new IllegalArgumentException("amount must be positive");
}
balance += amount;
}
public void withdraw(int amount) {
if (amount > balance) {
throw new IllegalStateException("insufficient funds");
}
balance -= amount;
}
}Writing Nested Tests
Here is a full test class that uses @Nested. Read it from top to bottom. Each level adds one more step to the setup.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
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("A bank account")
class BankAccountTest {
BankAccount account;
@BeforeEach
void createAccount() {
account = new BankAccount();
}
@Test
@DisplayName("starts with a balance of zero")
void startsAtZero() {
assertEquals(0, account.getBalance());
}
@Nested
@DisplayName("when new")
class WhenNew {
@Test
@DisplayName("rejects a withdrawal")
void rejectsWithdrawal() {
assertThrows(IllegalStateException.class, () -> account.withdraw(10));
}
@Test
@DisplayName("rejects a negative deposit")
void rejectsNegativeDeposit() {
assertThrows(IllegalArgumentException.class, () -> account.deposit(-5));
}
}
@Nested
@DisplayName("after depositing 100")
class AfterDeposit {
@BeforeEach
void depositMoney() {
account.deposit(100);
}
@Test
@DisplayName("has a balance of 100")
void hasBalance() {
assertEquals(100, account.getBalance());
}
@Test
@DisplayName("allows a smaller withdrawal")
void allowsSmallerWithdrawal() {
account.withdraw(30);
assertEquals(70, account.getBalance());
}
@Test
@DisplayName("rejects a larger withdrawal")
void rejectsLargerWithdrawal() {
assertThrows(IllegalStateException.class, () -> account.withdraw(150));
}
@Nested
@DisplayName("and withdrawing everything")
class AfterWithdrawingAll {
@BeforeEach
void withdrawAll() {
account.withdraw(100);
}
@Test
@DisplayName("has a balance of zero again")
void isEmptyAgain() {
assertEquals(0, account.getBalance());
}
}
}
}Look at these points:
WhenNew,AfterDeposit, andAfterWithdrawingAllare inner classes. An inner class is a class declared inside another class without thestatickeyword.- The inner classes use the
accountfield from the outer class. Java allows this because an inner class can see the fields of the class around it. AfterWithdrawingAllsits insideAfterDeposit. You can nest as deep as you like, though two or three levels is usually enough.
Reading the Results
The IDE and most build reports show nested tests as a tree. With the display names above, the result reads almost like a sentence:
A bank account
├─ starts with a balance of zero
├─ when new
│ ├─ rejects a withdrawal
│ └─ rejects a negative deposit
└─ after depositing 100
├─ has a balance of 100
├─ allows a smaller withdrawal
├─ rejects a larger withdrawal
└─ and withdrawing everything
└─ has a balance of zero againIf a test fails, you can see right away which state the account was in. "A bank account, after depositing 100, rejects a larger withdrawal" tells you much more than a method name on its own.
How Setup Runs in Nested Classes
When JUnit runs a test inside a nested class, it runs the @BeforeEach methods from the outside in. The outer class's setup runs first, then the next class in, and so on. @AfterEach methods run in the opposite order, from the inside out.
So for isEmptyAgain, the account is created, 100 is deposited, and 100 is withdrawn, all before the test body runs.
JUnit also creates new objects for every single test. Each test gets a new outer BankAccountTest object and a new object for every nested class it is in. One test cannot leave money behind for another test. This keeps the tests independent.
You can watch the order yourself with a few print statements:
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
class OrderTest {
@BeforeEach
void outerSetUp() {
System.out.println("outer before");
}
@AfterEach
void outerTearDown() {
System.out.println("outer after");
}
@Nested
class Inner {
@BeforeEach
void innerSetUp() {
System.out.println("inner before");
}
@AfterEach
void innerTearDown() {
System.out.println("inner after");
}
@Test
void innerTest() {
System.out.println("test");
}
}
}Running innerTest prints:
outer before
inner before
test
inner after
outer afterOuter Tests and Nested Tests Compared
| Question | Test in the outer class | Test in a nested class |
|---|---|---|
| Which `@BeforeEach` methods run? | Only the outer ones | Outer ones first, then each nested level |
| Can it use outer fields? | Yes | Yes, because it is an inner class |
| Needs `static`? | No | Must not be `static` |
| Shown in reports as | A direct child of the class | A child of its nested group |
Common Mistakes
Forgetting the @Nested annotation
If you write an inner class with tests but leave out @Nested, JUnit does not run those tests. Nothing fails, so the build looks green, but the tests never ran.
Making the nested class static
A nested test class must be an inner class, so it must not be static. A static class cannot see the outer class's instance fields such as account, and JUnit will not run it as a nested group. Delete the static keyword.
Using @BeforeAll in a nested class
@BeforeAll methods must normally be static. Older Java versions did not allow static methods inside inner classes. On Java 16 and later this works. On older Java, put @TestInstance(TestInstance.Lifecycle.PER_CLASS) on the nested class so its @BeforeAll method does not need to be static. Most of the time, @BeforeEach is all a nested class needs.
Nesting too deeply
Every level adds setup that a reader has to keep in mind. If you need four or five levels to reach a test, the class under test may be doing too much, or the test may fit better in a separate test class.
Exercises
Exercise
A test class has an inner class containing three @Test methods, but the inner class has no @Nested annotation. How many of those three tests run?
Show answer
None. JUnit only runs tests in inner classes that are marked with @Nested, and it skips the others without reporting a failure.
Exercise
The outer class has a @BeforeEach that creates a BankAccount, and a nested class has a @BeforeEach that deposits 50. In what order do these run before a test in the nested class?
Show answer
The outer @BeforeEach runs first and creates the account. Then the nested @BeforeEach deposits 50. Then the test runs.
Exercise
Add a nested class inside AfterDeposit called AfterSecondDeposit that deposits another 50 in its @BeforeEach, and a test that checks the balance. What value should the test expect?
Show answer
It should expect 150. The outer setup creates the account, AfterDeposit deposits 100, and AfterSecondDeposit deposits 50, so assertEquals(150, account.getBalance()) passes.
Exercise
Why can the test inside AfterWithdrawingAll use the account field even though that field is declared in BankAccountTest?
Show answer
AfterWithdrawingAll is a non-static inner class, so Java lets it reach the fields of the classes around it, including the account field in the outer class.