Unit Testing
Unit tests verify one class in isolation — typically an Orders service, mapper, or validator.
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/verifyfor 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
- Create
OrderServiceTestwith mocked repository and inventory client. - Stub stock reservation success and repository save.
- Call
placeand assert status + verifysave. - Add a failure case where inventory denies stock and no save occurs.
Informative example
Orders service unit test with Mockito.
@ExtendWith(MockitoExtension.class)class OrderServiceTest {@Mock OrderRepository repo;@Mock InventoryClient inventory;@InjectMocks OrderService svc;@Testvoid 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));}@Testvoid 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
@SpringBootTestfor pure unit cases and waiting minutes per run.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhat makes a test a unit test?+
Answer
2IntermediateQuestionWhy prefer constructor injection for testability?+
Answer
3IntermediateQuestionWhen is verify(never()) useful?+
Answer
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.