Testing
JUnit
The standard unit testing framework for Java and the JVM, the parent of the xUnit family.
What it is
Kent Beck and Erich Gamma created JUnit in 1997, and it became the basis for xUnit tools in other languages. Modern JUnit 5 has three parts: Platform (running), Jupiter (the new programming model and annotations) and Vintage (compatibility with old JUnit 3 and 4 tests).
Tests are methods annotated @Test. There are @BeforeEach, @AfterEach, parameterized tests (@ParameterizedTest), nested classes (@Nested) and extensions. Assertions come from Assertions or third-party AssertJ and Hamcrest.
JUnit integrates with Maven, Gradle and IDEs. It is usually paired with Mockito for mocks, and in Spring Boot it is the default testing base.
Use it when
- Unit and integration tests for Java and Kotlin on the JVM.
- Spring Boot projects: JUnit is the standard.
- You need parametrization, nested tests and extensions.
Avoid it when
- Tests not on the JVM.
- UI and browser end-to-end tests: use Playwright or Selenium (JUnit only runs them).
Key concepts
- @Test and lifecycle
@BeforeEach,@AfterEach,@BeforeAlland@AfterAllmanage setup.- Assertions
assertEquals,assertThrowsandassertAllcheck results.- Parameterized tests
- One test runs over a data set from
@ValueSourceor@CsvSource. - Extensions
- The
@ExtendWithmechanism for mocks, Spring and Testcontainers. - Nested tests
@Nestedclasses group scenarios with shared state.
Example
Interview questions
1. What does JUnit 5 consist of?
Three parts: Platform runs tests, Jupiter provides the new API and annotations, Vintage runs old JUnit 3 and 4 tests.
2. How do you check that a method throws an exception?
With
assertThrows(IllegalArgumentException.class, () -> service.run()). The method returns the exception so you can assert further.3. How does @BeforeEach differ from @BeforeAll?
@BeforeEachruns before each test,@BeforeAllruns once before all tests in the class and must be static (unless@TestInstance(PER_CLASS)).4. Why Mockito together with JUnit?
JUnit runs tests and checks results, while Mockito creates stubs of dependencies to isolate the class under test from the database, network and other services.
Related technologies
- JavaA statically typed JVM language: the base of enterprise backends, Android and large systems.
- KotlinA modern concise language for the JVM, Android and multiplatform development, fully interoperable with Java.
- Spring BootAn opinionated layer over Spring for Java and Kotlin with auto-configuration and one-command startup.
Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).