liminfo

JUnit Reference

Free reference guide: JUnit Reference

40 results

About JUnit Reference

The JUnit 5 Reference is a complete, searchable guide to the JUnit Jupiter testing framework for Java. It covers all eight categories of JUnit 5 features: Annotations (@Test, @DisplayName, @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, @Disabled, @Tag, @Timeout), Assertions (assertEquals, assertTrue, assertNull, assertThrows, assertAll, assertArrayEquals, assertIterableEquals), Parameterized Tests (@ParameterizedTest with @ValueSource, @CsvSource, @EnumSource, @MethodSource, @CsvFileSource), Lifecycle (@TestInstance, @TestMethodOrder, @RepeatedTest, TestInfo injection), Extensions (@ExtendWith, BeforeEachCallback, ParameterResolver, @RegisterExtension), Conditional Execution (@EnabledOnOs, @EnabledOnJre, @EnabledIfEnvironmentVariable, @EnabledIf), Nested Tests (@Nested with scoped lifecycle), and Configuration (build.gradle, pom.xml, junit-platform.properties, parallel execution). Every entry includes a real, runnable Java code example.

This reference is aimed at Java backend developers, QA engineers, and engineering teams adopting test-driven development (TDD) or behavior-driven development (BDD) practices. JUnit 5 is the dominant unit testing framework for Java applications built with Spring Boot, Quarkus, Micronaut, and standard Maven or Gradle projects. Whether you are writing your first unit test, setting up a CI/CD pipeline, or migrating from JUnit 4, this guide provides the exact annotations, assertions, and configuration syntax you need without switching to documentation pages.

The reference is organized into eight clearly defined categories so you can jump directly to the relevant section — whether you need to look up the correct assertion method, find how to configure parameterized test data sources, or review the extension API for custom test infrastructure. Each entry shows syntax and a focused, self-contained code example so you can understand the concept and apply it immediately.

Key Features

  • Complete JUnit 5 annotation reference: @Test, @DisplayName, @BeforeEach, @AfterEach, @BeforeAll, @AfterAll, @Disabled, @Tag, @Timeout
  • Assertion methods with examples: assertEquals, assertTrue, assertThrows (with message capture), assertAll for grouped assertions, and array/iterable comparison
  • Parameterized test sources: @ValueSource, @CsvSource (inline and file), @EnumSource, and @MethodSource with Stream<Arguments>
  • Lifecycle control: @TestInstance(PER_CLASS) for shared state, @TestMethodOrder with @Order, @RepeatedTest with RepetitionInfo
  • Extension API: @ExtendWith, BeforeEachCallback, ParameterResolver, and @RegisterExtension for programmatic setup
  • Conditional test execution based on OS (@EnabledOnOs), JRE version (@EnabledOnJre), environment variable, and custom boolean methods
  • @Nested test classes for organizing related test cases with inner-class scoped @BeforeEach lifecycle methods
  • Gradle and Maven dependency configuration, junit-platform.properties for default settings, and parallel execution setup

Frequently Asked Questions

What is the difference between @BeforeEach and @BeforeAll in JUnit 5?

@BeforeEach runs before every individual test method in the class, making it ideal for setting up fresh object instances. @BeforeAll runs once before all tests in the class and must be static (unless using @TestInstance(PER_CLASS)). Use @BeforeAll for expensive setup like database connections that are safe to share across tests.

How do I test that a method throws an exception in JUnit 5?

Use assertThrows(ExceptionType.class, () -> { /* code */ }). It returns the thrown exception so you can also assert on its message or cause: `Exception ex = assertThrows(IllegalArgumentException.class, () -> calc.divide(1, 0)); assertEquals("Cannot divide by zero", ex.getMessage());`

How do I run the same test with multiple input values in JUnit 5?

Use @ParameterizedTest combined with a value source annotation. For simple values use @ValueSource. For multiple parameters per test, use @CsvSource with inline CSV strings or @CsvFileSource to read from a CSV file. For complex objects, use @MethodSource with a static method returning Stream<Arguments>.

What is assertAll() and when should I use it?

assertAll() groups multiple assertions and runs all of them even if some fail, then reports all failures together. This gives you a complete picture of what is wrong rather than stopping at the first failed assertion. Use it when you want to verify multiple properties of an object in a single test.

How do I configure JUnit 5 in a Gradle project?

Add `testImplementation "org.junit.jupiter:junit-jupiter:5.10.0"` to your dependencies block, and add `test { useJUnitPlatform() }` to your test task. Without useJUnitPlatform(), Gradle will not discover JUnit 5 tests. For Maven, add the junit-jupiter dependency with test scope and configure the maven-surefire-plugin.

How do I organize related tests in JUnit 5?

Use @Nested to create inner test classes that group related test scenarios. Nested classes can have their own @BeforeEach and @AfterEach methods that compose with the outer class lifecycle. This is useful for describing different states (e.g., WhenEmpty, WhenNotEmpty) and produces a readable, hierarchical test report.

How do I run JUnit 5 tests only on a specific OS or Java version?

Use conditional execution annotations: @EnabledOnOs(OS.LINUX) restricts a test to Linux, @EnabledOnOs({OS.WINDOWS, OS.MAC}) enables it on multiple platforms. @EnabledOnJre(JRE.JAVA_17) runs the test only on Java 17. For environment-based conditions, use @EnabledIfEnvironmentVariable(named = "ENV", matches = "staging").

How do I enable parallel test execution in JUnit 5?

Create src/test/resources/junit-platform.properties and add: `junit.jupiter.execution.parallel.enabled = true`, `junit.jupiter.execution.parallel.mode.default = concurrent`, and `junit.jupiter.execution.parallel.config.fixed.parallelism = 4`. Note that parallel execution requires your tests to be thread-safe and not share mutable static state.