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

    Unit Testing

    Unit tests verify a single class in isolation: services, mappers, validators.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Unit tests verify a single class in isolation: services, mappers, validators. Mock collaborators with Mockito; use JUnit 5 assertions.

    Informative example

    ts
    class OrderServiceTest {
    @Mock OrderRepository repo;
    @Mock InventoryClient inventory;
    @InjectMocks OrderService svc;
    @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); }
    @Test void placesOrderWhenStockAvailable() {
    when(inventory.reserve(any())).thenReturn(true);
    when(repo.save(any())).thenAnswer(a -> a.getArgument(0));
    OrderDto result = svc.place(new NewOrder(1L, List.of(new LineItem(10L, 2)), "USD"));
    assertEquals(OrderStatus.PLACED, result.status());
    verify(repo).save(any(Order.class));
    }
    }

    Best practices

    • One assertion concept per test; descriptive names.
    • AAA — Arrange, Act, Assert.
    • Mock only what you own; don't mock JDK or Spring.
    Ready to mark this lesson complete?Track your journey across the entire course.