home / skills / mduongvandinh / skills-java-spring / spring-tdd-mockito

This skill guides TDD with Mockito for Spring Boot, enabling you to write tests first and streamline red-green-refactor cycles.

npx playbooks add skill mduongvandinh/skills-java-spring --skill spring-tdd-mockito

Review the files below or copy the command above to add this skill to your agents.

Files (1)
SKILL.md
2.8 KB
---
name: spring-tdd-mockito
version: 1.0.0
description: |
  TDD (Test-Driven Development) skill with Mockito for Spring Boot.
  Guides the Red-Green-Refactor cycle for writing tests first.

triggers:
  - "write test"
  - "tdd"
  - "mockito"
  - "unit test"
  - "test first"
---

# Spring Boot TDD with Mockito

## TDD Cycle: Red → Green → Refactor

```
┌─────────────────────────────────────────────────────────────┐
│                     TDD WORKFLOW                             │
│                                                              │
│   ┌───────┐      ┌───────┐      ┌──────────┐               │
│   │  RED  │ ───→ │ GREEN │ ───→ │ REFACTOR │ ───┐          │
│   │       │      │       │      │          │    │          │
│   │ Write │      │ Write │      │ Improve  │    │          │
│   │ Test  │      │ Code  │      │ Code     │    │          │
│   └───────┘      └───────┘      └──────────┘    │          │
│       ↑                                          │          │
│       └──────────────────────────────────────────┘          │
└─────────────────────────────────────────────────────────────┘
```

## Mockito Annotations

| Annotation | Purpose |
|------------|---------|
| `@Mock` | Create mock object |
| `@InjectMocks` | Inject mocks into class under test |
| `@Spy` | Partial mock - real methods + mock behavior |
| `@Captor` | Capture arguments passed to mock |
| `@MockBean` | Mock bean in Spring context |

## Test Template

```java
@ExtendWith(MockitoExtension.class)
class ServiceTest {

    @Mock
    private Repository repository;

    @InjectMocks
    private Service service;

    @Test
    @DisplayName("Should do something when condition is met")
    void shouldDoSomethingWhenConditionIsMet() {
        // Given (Arrange)
        when(repository.findById(1L)).thenReturn(Optional.of(entity));

        // When (Act)
        var result = service.doSomething(1L);

        // Then (Assert)
        assertThat(result).isNotNull();
        verify(repository).findById(1L);
    }
}
```

## Best Practices

1. **One assertion per test** - Focus on single behavior
2. **Descriptive test names** - Use `@DisplayName`
3. **AAA Pattern** - Arrange, Act, Assert
4. **Test behavior, not implementation**
5. **Fast tests** - Mock external dependencies
6. **Isolated tests** - No shared state

Overview

This skill guides developers through Test-Driven Development (TDD) for Spring Boot using Mockito. It focuses on the Red→Green→Refactor cycle and provides practical templates and patterns to write tests first. The goal is fast, isolated unit tests that drive design and ensure behavior. It is aimed at Java developers using Spring Boot and Mockito for mocking dependencies.

How this skill works

The skill walks through the TDD workflow: write a failing test (Red), implement the minimal code to pass (Green), then improve design and refactor while keeping tests green. It provides Mockito-based test templates using @Mock, @InjectMocks, @Spy, @Captor, and @MockBean to isolate units and mock Spring beans. Examples follow the Arrange-Act-Assert (AAA) pattern and emphasize one focused assertion per test.

When to use it

  • When designing new Spring services and you want tests to drive the API and behavior
  • When replacing slow or brittle integration tests with fast unit tests that mock dependencies
  • When refactoring legacy code to ensure behavior is preserved
  • When onboarding developers to consistent testing patterns and naming conventions
  • When needing reproducible, fast feedback during development

Best practices

  • Follow the Red → Green → Refactor cycle strictly to keep scope minimal
  • Use the AAA pattern: Arrange, Act, Assert in each test
  • Prefer one behavior assertion per test to keep intent clear
  • Write descriptive test names with @DisplayName or readable method names
  • Mock external dependencies to keep tests fast and isolated
  • Test behavior, not implementation; avoid over-coupling to internals

Example use cases

  • Unit testing a Spring service that reads from a repository: mock repository calls and verify interactions
  • Driving the design of a new API by writing failing tests that describe required behavior first
  • Refactoring a service implementation while preserving behavior via a comprehensive test suite
  • Replacing integration tests with unit tests for business logic that depends on external systems
  • Capturing method arguments with @Captor to assert how dependencies are used

FAQ

When should I use @MockBean vs @Mock?

@MockBean is for replacing beans in the Spring test context (integration slice); use @Mock for plain unit tests with MockitoExtension where you don't load Spring.

How many assertions per test are ideal?

Aim for a single, focused assertion per test that validates one observable behavior. Additional verifications of interactions are acceptable if they are part of the same behavior.