Video in progress
What do @Nested test classes give you, and how are they structured?
@Nested groups tests by state or scenario using inner (non-static) classes. Each inner class inherits the outer class's @BeforeEach and adds its own.
📖 Answer
When one class has 30 tests, they blur together in a flat list. With @Nested they become a tree:
class AccountTest {
Account account;
@BeforeEach
void init() { account = new Account(); }
@Nested
class YangiOchilganHisob {
@Test void balans_nol() { assertEquals(BigDecimal.ZERO, account.balance()); }
@Test void yechish_rad_etiladi() { assertFalse(account.withdraw(TEN).isSuccess()); }
}
@Nested
class PulQoyilganHisob {
@BeforeEach
void deposit() { account.deposit(new BigDecimal("100")); }
@Test void qisman_yechish_mumkin() { assertTrue(account.withdraw(TEN).isSuccess()); }
}
}
In the PulQoyilganHisob test, the outer init runs first, then the inner deposit.
In the report the tests appear as "AccountTest > PulQoyilganHisob > qisman_yechish_mumkin", which reads like a specification.
Limits: the inner class must not be static, otherwise JUnit treats it as an ordinary separate class. Going more than three levels deep makes it hard to read again.
Sign up to mark studied questions and save your progress.