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, @BeforeAll and @AfterAll manage setup.
Assertions
assertEquals, assertThrows and assertAll check results.
Parameterized tests
One test runs over a data set from @ValueSource or @CsvSource.
Extensions
The @ExtendWith mechanism for mocks, Spring and Testcontainers.
Nested tests
@Nested classes group scenarios with shared state.

Example

A JUnit 5 parameterized test.

Interview questions

  1. 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. 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. 3. How does @BeforeEach differ from @BeforeAll?

    @BeforeEach runs before each test, @BeforeAll runs once before all tests in the class and must be static (unless @TestInstance(PER_CLASS)).

  4. 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.

Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).