Nested test classes
A basket has one group of tests for the empty basket and another for the basket with an apple. Written flat, the names grow a prefix that repeats the group. A @Nested class puts the group back into the code and into the report, and the outer fixture still runs around every inner test.
One class, two groups
BasketTest.java has an outer test for the empty basket and a nested class for the basket with one item. The nested class is an inner class, so it sees the outer field, and its own @BeforeEach fills it.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
public class BasketTest {
private List<String> items;
@BeforeEach
void createBasket() {
items = new ArrayList<>();
}
@Test
void startsEmpty() {
assertTrue(items.isEmpty());
}
@Nested
class WithOneItem {
@BeforeEach
void addItem() {
items.add("apple");
}
@Test
void hasOneItem() {
assertEquals(1, items.size());
}
@Test
void hasAnApple() {
assertEquals("apple", items.get(0));
}
}
}
@Nested
The annotation marks an inner class as a group of tests. The class is not static, because it needs the outer instance and its fields; a static nested class with the annotation is rejected. It may have its own @BeforeEach, @AfterEach, @Test methods and further nested classes.
The nested class is part of the outer test class, so the launcher finds it without a separate scan and the counts table counts one more container. The tree shows the group as a branch under the outer class, which is the report form of the code structure.
The outer fixture
For an inner test, Jupiter runs the outer @BeforeEach first and then the inner one. The order matters: the outer method created the list, and the inner method added the apple to it. On the way out, the inner @AfterEach runs before the outer one, the reverse of the setup order.
The outer test startsEmpty does not see the inner @BeforeEach: it is not part of that group. That is the point of the split, and it is why a group should hold only the tests that need its extra setup.
The report and its extra container
javac -Xlint:all -cp /opt/java-tools/junit-platform-console-standalone.jar -d out BasketTest.java
junit execute --class-path out --scan-classpath --disable-ansi-colors
Thanks for using JUnit! Support its development at https://junit.org/sponsoring
╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
│ └─ BasketTest ✔
│ ├─ startsEmpty() ✔
│ └─ WithOneItem ✔
│ ├─ hasOneItem() ✔
│ └─ hasAnApple() ✔
└─ JUnit Vintage ✔
Test run finished after 367 ms
[ 5 containers found ]
[ 0 containers skipped ]
[ 5 containers started ]
[ 0 containers aborted ]
[ 5 containers successful ]
[ 0 containers failed ]
[ 3 tests found ]
[ 0 tests skipped ]
[ 3 tests started ]
[ 0 tests aborted ]
[ 3 tests successful ]
[ 0 tests failed ]
The counts show five containers where the flat class had four: the nested class is a container of its own. The tests are still three, because the group holds tests, not a fourth test.
Names and limits
A nested class can carry @DisplayName, and the tree then shows the sentence instead of the class name. A deep group nests again, and the tree indents again; two levels are usually enough, and a third is a sign that the class is doing too much.
The nested class cannot be private if the launcher must construct it, and it cannot be static. It inherits the outer class's annotations for the report, so a @Tag on the outer class applies to the inner tests as well.
Exercises
- Add a second item to the nested fixture and a test for the size. How many tests and containers does the report count?
- Remove @Nested and run. What changes in the tree and in the container count?
- Add @DisplayName("an empty basket") to the outer test and read the tree line.
- Add an @AfterEach to the nested class that clears the list, and explain why the outer test still sees an empty list.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
@Nestedadd to the counts table?Answer
One container
The nested class is a container of tests, so containers grow by one while tests do not.
-
In which order do the fixtures run for an inner test?
Answer
The outer @BeforeEach, then the inner @BeforeEach
The outer fixture creates the shared object, and the inner one adds to it.
-
Why can a
@Nestedclass not be static?Answer
It needs the outer instance and its fields
The inner class reads the outer fixture, so it must be an inner class.
-
What does this program print?
public class Q1 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); items.add("apple"); System.out.println(items.size()); } }Answer
1
One item was added, so the size is 1.
-
What does this program print?
public class Q2 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); items.add("apple"); System.out.println(items.get(0)); } }Answer
apple
The first element is the string apple.
-
What does this program print?
public class Q3 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); System.out.println(items.isEmpty()); } }Answer
true
A new list has no elements, so isEmpty is true.
-
What does this program print?
public class Q4 { public static void main(String[] args) { String text = "apple"; System.out.println(text.substring(0, 2)); } }Answer
ap
The substring starts at 0 and stops before index 2, so it is ap.
-
Does an inner test see the outer
@BeforeEach?Answer
Yes, it runs before the inner one
The outer fixture surrounds every test of the class, including the nested ones.
-
What does this program print?
public class Q5 { public static void main(String[] args) { java.util.List<String> items = new java.util.ArrayList<>(); items.add("apple"); items.add("pear"); System.out.println(items.size() + items.get(1).length()); } }Answer
6
The size is 2 and pear has four letters, so the sum is 6.
-
What is the usual limit on nesting test classes?
Answer
Two levels, because a deeper tree is hard to read
Deep nesting makes the report and the class hard to follow; two levels cover most groups.
The code on this page was built with OpenJDK 21.0.13 (javac) and run with JUnit Platform Console Launcher 1.14.3 on Alpine Linux in a Docker container.
Article author: Arthur Isaev