Java Tutorial 0/145 lessons ~6 min read Lesson 75

    JUnit 5

    junit 5 junit 5 (jupiter) is the standard test framework for java. annotations like @test, @beforeeach, @parameterizedtest and @nested structure your test

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    JUnit 5 (Jupiter) is the standard test framework for Java. Annotations like @Test, @BeforeEach, @ParameterizedTest and @Nested structure your test suite; assertions come from AssertJ or Hamcrest.

    Informative example

    JUnit 5 test class:

    ts
    @DisplayName("OrderService tests")
    class OrderServiceTest {
    OrderService service;
    OrderRepository mockRepo;
    @BeforeEach
    void setUp() {
    mockRepo = mock(OrderRepository.class);
    service = new OrderService(mockRepo, mockGateway);
    }
    @Test
    @DisplayName("should create order with valid request")
    void createOrder() {
    var req = new OrderRequest("SKU-1", 2);
    when(mockRepo.save(any())).thenAnswer(i -> i.getArgument(0));
    Order result = service.place(req);
    assertThat(result.sku()).isEqualTo("SKU-1");
    verify(mockRepo).save(any(Order.class));
    }
    @ParameterizedTest
    @ValueSource(ints = {0, -1, 10001})
    void rejectsInvalidQuantity(int qty) {
    assertThrows(IllegalArgumentException.class,
    () -> service.place(new OrderRequest("X", qty)));
    }
    }

    Best practices

    • One assertion concept per test — name tests after behaviour.
    • Use @Nested to group related tests by scenario.
    • Prefer AssertJ (assertThat) over JUnit's assertEquals.

    Purpose of this lesson

    Master JUnit 5 so you can apply it confidently in production Java code, technical interviews, and code reviews.

    Step-by-step explanation

    1. Understand the core idea behind JUnit 5.
    2. Walk through the runnable example and tweak it in the playground.
    3. Apply the pattern in a small Spring Boot or CLI exercise of your own.
    4. Re-read the common mistakes and interview Q&A to lock the concept in.

    Interactive workflow diagram

    1JUnit 5 — typical flow
    1 / 4

    Identify use case

    Recognize when junit 5 is the right tool for the problem.

    Useful template

    JUnit 5 test skeleton

    java
    @ExtendWith(MockitoExtension.class)
    class MyServiceTest {
    @Mock Dependency dep;
    @InjectMocks MyService service;
    @BeforeEach void setUp() { /* ... */ }
    @Test
    @DisplayName("should do X when Y")
    void testScenario() {
    when(dep.call()).thenReturn(expected);
    assertThat(service.run()).isEqualTo(expected);
    }
    }

    Debugging tips

    • Read the full stack trace — Java's exception messages name the offending class and line.
    • Reproduce in the smallest possible main() method before fixing in the real app.
    • Use IntelliJ's debugger breakpoints and 'Evaluate Expression' rather than scattering System.out.

    Optimization strategies

    • Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
    • Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
    • Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.

    Enterprise example

    Teams at Netflix, Uber and Goldman Sachs apply JUnit 5 daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).

    Interview questions & answers

    Q1Explain JUnit 5 in one minute.
    Describe what problem it solves, the JDK APIs involved, and one production trade-off.
    Q2When would you avoid JUnit 5?
    Mention performance, complexity, or readability cases where a simpler approach wins.

    Summary

    In this lesson you learned JUnit 5 — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.

    Ready to mark this lesson complete?Track your journey across the entire course.