Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 64

    Unit Testing

    Unit tests verify one class in isolation — typically an Orders service, mapper, or validator.

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

    Introduction

    Unit tests verify one class in isolation — typically an Orders service, mapper, or validator. Collaborators are mocked (Mockito); the Spring context stays out so suites stay fast.

    On Boot 3 / JUnit 5, prefer constructor injection in production code so @InjectMocks or plain constructors work cleanly in tests. Assert behaviour and interactions, not private implementation details.

    Unit tests are not integration tests: no real Postgres, no full @SpringBootTest. That speed lets TechLearningPRO engineers run hundreds of Orders cases on every commit.

    This lesson builds the fast inner loop before Testcontainers-based integration tests.

    Purpose of this lesson

    Write fast JUnit 5 + Mockito unit tests for Orders services without starting the Spring context.

    Understanding the topic

    Arrange → Act → Assert on one unit; mock the rest.

    • JUnit 5: @Test, lifecycle callbacks, assertions.
    • Mockito: when/verify for collaborators.
    • AAA: arrange data, act on the method, assert outcomes.
    • Names: behaviour-focused (placesOrderWhenStockAvailable).
    • Scope: no HTTP, no DB, no full context.

    Step-by-step explanation

    1. Create OrderServiceTest with mocked repository and inventory client.
    2. Stub stock reservation success and repository save.
    3. Call place and assert status + verify save.
    4. Add a failure case where inventory denies stock and no save occurs.

    Informative example

    Orders service unit test with Mockito.

    java
    @ExtendWith(MockitoExtension.class)
    class OrderServiceTest {
    @Mock OrderRepository repo;
    @Mock InventoryClient inventory;
    @InjectMocks OrderService svc;
    @Test
    void placesOrderWhenStockAvailable() {
    when(inventory.reserve(any())).thenReturn(true);
    when(repo.save(any())).thenAnswer(a -> a.getArgument(0));
    OrderView result = svc.place(new CreateOrderRequest(1L, List.of(new LineItem(10L, 2)), "USD"));
    assertEquals(OrderStatus.PLACED, result.status());
    verify(repo).save(any(OrderEntity.class));
    }
    @Test
    void doesNotSaveWhenStockMissing() {
    when(inventory.reserve(any())).thenReturn(false);
    assertThrows(ConflictException.class,
    () -> svc.place(new CreateOrderRequest(1L, List.of(new LineItem(10L, 2)), "USD")));
    verify(repo, never()).save(any());
    }
    }

    Real-world use

    A pricing rule bug once shipped because only MockMvc happy-path tests existed. A focused unit test on OrderService.place with denied inventory would have failed in seconds. TechLearningPRO now requires service-level unit coverage for every checkout branch before integration tests.

    Security implications

    Tests must not embed production secrets.

    • Use fake credentials and in-memory stubs only.
    • Assert that unauthorized paths throw domain/security exceptions where relevant.
    • Never commit real API tokens in test fixtures.

    Best practices

    • One behavioural assertion cluster per test; descriptive names.
    • Prefer AssertJ for fluent assertions when the team standard allows.
    • Keep tests deterministic — no real clocks/network without fakes.

    Common mistakes

    • Mocking the class under test or over-mocking value objects.
    • Testing private methods instead of observable behaviour.
    • Using @SpringBootTest for pure unit cases and waiting minutes per run.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhat makes a test a unit test?+

    Answer

    It exercises one unit with collaborators replaced by doubles, without a full container or real I/O.
    2IntermediateQuestionWhy prefer constructor injection for testability?+

    Answer

    Tests can new up the service with mocks directly; field injection fights plain unit tests.
    3IntermediateQuestionWhen is verify(never()) useful?+

    Answer

    To prove side effects did not happen on failure paths — e.g. no save after stock denial.

    Hands-on exercise

    Lab. Implement the two tests above against your OrderService. Add a third that verifies an outbox publish is invoked once on success.

    Summary

    Unit tests guard Orders business rules in milliseconds. Next: integration tests with a real Spring context and Testcontainers.

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