| name | unit-test-service-layer |
| description | Provides patterns for unit testing service layer with Mockito. Creates isolated tests that mock repository calls, verify method invocations, test exception scenarios, and stub external API responses. Use when testing service behaviors and business logic without database or external services. |
| allowed-tools | Read, Write, Bash, Glob, Grep |
Unit Testing Service Layer with Mockito
Overview
Provides patterns for unit testing @Service classes using Mockito. Mocks repository calls, verifies method invocations, tests exception scenarios, and stubs external API responses. Enables fast, isolated tests without Spring container or database.
When to Use
- Testing business logic in
@Service classes
- Mocking repository and external client dependencies
- Verifying service interactions with mocked collaborators
- Testing error handling and edge cases in services
- Writing fast, isolated unit tests (no database, no API calls)
Instructions
Follow this workflow to test service layer with Mockito, including validation checkpoints:
1. Setup Test Class
Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations.
2. Declare Mocks with @Mock and @InjectMocks
Use @Mock for dependencies (repositories, clients) and @InjectMocks for the service under test.
3. Arrange-Act-Assert with Validation
Arrange: Create test data and configure mock return values using .