springboot-tdd

Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

144,923 stars
Complexity: easy

About this skill

This skill provides a structured, step-by-step workflow for AI agents to perform Test-driven development (TDD) within Spring Boot applications. It comprehensively covers the use of essential testing tools and frameworks, including JUnit 5 for core unit testing, Mockito for mocking dependencies, MockMvc for testing REST endpoints without a running server, Testcontainers for reliable integration tests with real databases or services, and JaCoCo for enforcing and reporting code coverage. The skill emphasizes writing failing tests first, implementing minimal code to pass tests, and then refactoring, ensuring an 80%+ test coverage target. It's designed to enhance the development of new features, bug fixes, and refactoring efforts by promoting best practices in software testing and quality assurance.

Best use case

Implementing new features or API endpoints, fixing bugs, refactoring existing code, or adding data access logic and security rules within Spring Boot applications following TDD principles.

Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

Well-tested Spring Boot code with high unit and integration test coverage (target 80%+), improved code quality, fewer bugs, and a clear, maintainable codebase that adheres to TDD best practices. The AI agent will deliver code that demonstrates a robust testing strategy.

Practical example

Example input

Using the `springboot-tdd` skill, implement a new Spring Boot service for managing `Product` entities. The service should include basic CRUD operations (create, retrieve, update, delete). Ensure all development follows the TDD workflow, utilizing JUnit 5, Mockito for service-layer tests, MockMvc for controller tests, and Testcontainers for persistence layer integration tests with a PostgreSQL database. Aim for over 80% code coverage.

Example output

The AI agent will generate:
1.  A series of failing unit tests (e.g., `ProductServiceTest`, `ProductControllerTest`) defining the expected behavior for CRUD operations.
2.  Minimal Spring Boot service, repository, and controller implementation code required to make the initial tests pass.
3.  Refactored and optimized code, ensuring all tests remain green while adhering to Spring Boot best practices and clean code principles.
4.  Integration tests for the persistence layer using Testcontainers (e.g., against a PostgreSQL instance) to validate database interactions.
5.  Updated `pom.xml` or `build.gradle` configuration to include JaCoCo for code coverage enforcement.
6.  An assessment of the code coverage achieved, aiming for the 80%+ target.
7.  Detailed code snippets and explanations of the generated tests and application logic.

When to use this skill

  • When developing or modifying Spring Boot applications and aiming for high code quality, maintainability, and reliability through a disciplined TDD approach. Ideal for ensuring new functionality is robust, bug fixes are thoroughly validated, and the codebase adheres to professional standards.

When not to use this skill

  • When working on simple, throwaway scripts or prototypes where the overhead of comprehensive testing and TDD methodology is not justified. This skill is specifically tailored for Spring Boot projects using Java, so it's not suitable for projects based on other frameworks or languages.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/springboot-tdd/SKILL.md --create-dirs "https://raw.githubusercontent.com/affaan-m/everything-claude-code/main/docs/ja-JP/skills/springboot-tdd/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/springboot-tdd/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How springboot-tdd Compares

Feature / Agentspringboot-tddStandard Approach
Platform SupportClaudeLimited / Varies
Context Awareness High Baseline
Installation ComplexityeasyN/A

Frequently Asked Questions

What does this skill do?

Test-driven development for Spring Boot using JUnit 5, Mockito, MockMvc, Testcontainers, and JaCoCo. Use when adding features, fixing bugs, or refactoring.

Which AI agents support this skill?

This skill is designed for Claude.

How difficult is it to install?

The installation complexity is rated as easy. You can find the installation instructions above.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

Related Guides

SKILL.md Source

# Spring Boot TDD ワークフロー

80%以上のカバレッジ(ユニット+統合)を持つSpring Bootサービスのためのテスト駆動開発ガイダンス。

## いつ使用するか

- 新機能やエンドポイント
- バグ修正やリファクタリング
- データアクセスロジックやセキュリティルールの追加

## ワークフロー

1) テストを最初に書く(失敗すべき)
2) テストを通すための最小限のコードを実装
3) テストをグリーンに保ちながらリファクタリング
4) カバレッジを強制(JaCoCo)

## ユニットテスト(JUnit 5 + Mockito)

```java
@ExtendWith(MockitoExtension.class)
class MarketServiceTest {
  @Mock MarketRepository repo;
  @InjectMocks MarketService service;

  @Test
  void createsMarket() {
    CreateMarketRequest req = new CreateMarketRequest("name", "desc", Instant.now(), List.of("cat"));
    when(repo.save(any())).thenAnswer(inv -> inv.getArgument(0));

    Market result = service.create(req);

    assertThat(result.name()).isEqualTo("name");
    verify(repo).save(any());
  }
}
```

パターン:
- Arrange-Act-Assert
- 部分モックを避ける。明示的なスタビングを優先
- バリエーションに`@ParameterizedTest`を使用

## Webレイヤーテスト(MockMvc)

```java
@WebMvcTest(MarketController.class)
class MarketControllerTest {
  @Autowired MockMvc mockMvc;
  @MockBean MarketService marketService;

  @Test
  void returnsMarkets() throws Exception {
    when(marketService.list(any())).thenReturn(Page.empty());

    mockMvc.perform(get("/api/markets"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.content").isArray());
  }
}
```

## 統合テスト(SpringBootTest)

```java
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
class MarketIntegrationTest {
  @Autowired MockMvc mockMvc;

  @Test
  void createsMarket() throws Exception {
    mockMvc.perform(post("/api/markets")
        .contentType(MediaType.APPLICATION_JSON)
        .content("""
          {"name":"Test","description":"Desc","endDate":"2030-01-01T00:00:00Z","categories":["general"]}
        """))
      .andExpect(status().isCreated());
  }
}
```

## 永続化テスト(DataJpaTest)

```java
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Import(TestContainersConfig.class)
class MarketRepositoryTest {
  @Autowired MarketRepository repo;

  @Test
  void savesAndFinds() {
    MarketEntity entity = new MarketEntity();
    entity.setName("Test");
    repo.save(entity);

    Optional<MarketEntity> found = repo.findByName("Test");
    assertThat(found).isPresent();
  }
}
```

## Testcontainers

- 本番環境を反映するためにPostgres/Redis用の再利用可能なコンテナを使用
- `@DynamicPropertySource`経由でJDBC URLをSpringコンテキストに注入

## カバレッジ(JaCoCo)

Mavenスニペット:
```xml
<plugin>
  <groupId>org.jacoco</groupId>
  <artifactId>jacoco-maven-plugin</artifactId>
  <version>0.8.14</version>
  <executions>
    <execution>
      <goals><goal>prepare-agent</goal></goals>
    </execution>
    <execution>
      <id>report</id>
      <phase>verify</phase>
      <goals><goal>report</goal></goals>
    </execution>
  </executions>
</plugin>
```

## アサーション

- 可読性のためにAssertJ(`assertThat`)を優先
- JSONレスポンスには`jsonPath`を使用
- 例外には: `assertThatThrownBy(...)`

## テストデータビルダー

```java
class MarketBuilder {
  private String name = "Test";
  MarketBuilder withName(String name) { this.name = name; return this; }
  Market build() { return new Market(null, name, MarketStatus.ACTIVE); }
}
```

## CIコマンド

- Maven: `mvn -T 4 test` または `mvn verify`
- Gradle: `./gradlew test jacocoTestReport`

**覚えておいてください**: テストは高速で、分離され、決定論的に保ちます。実装の詳細ではなく、動作をテストします。

Related Skills

springboot-verification

144923
from affaan-m/everything-claude-code

Verification loop for Spring Boot projects: build, static analysis, tests with coverage, security scans, and diff review before release or PR.

DevelopmentClaude

springboot-security

144923
from affaan-m/everything-claude-code

Spring Security best practices for authn/authz, validation, CSRF, secrets, headers, rate limiting, and dependency security in Java Spring Boot services.

DevelopmentClaude

springboot-patterns

144923
from affaan-m/everything-claude-code

Spring Boot architecture patterns, REST API design, layered services, data access, caching, async processing, and logging. Use for Java Spring Boot backend work.

DevelopmentClaude

workspace-surface-audit

144923
from affaan-m/everything-claude-code

Audit the active repo, MCP servers, plugins, connectors, env surfaces, and harness setup, then recommend the highest-value ECC-native skills, hooks, agents, and operator workflows. Use when the user wants help setting up Claude Code or understanding what capabilities are actually available in their environment.

DevelopmentClaude

safety-guard

144923
from affaan-m/everything-claude-code

Use this skill to prevent destructive operations when working on production systems or running agents autonomously.

DevelopmentClaude

repo-scan

144923
from affaan-m/everything-claude-code

Cross-stack source code asset audit — classifies every file, detects embedded third-party libraries, and delivers actionable four-level verdicts per module with interactive HTML reports.

DevelopmentClaude

project-flow-ops

144923
from affaan-m/everything-claude-code

Operate execution flow across GitHub and Linear by triaging issues and pull requests, linking active work, and keeping GitHub public-facing while Linear remains the internal execution layer. Use when the user wants backlog control, PR triage, or GitHub-to-Linear coordination.

DevelopmentClaude

manim-video

144923
from affaan-m/everything-claude-code

Build reusable Manim explainers for technical concepts, graphs, system diagrams, and product walkthroughs, then hand off to the wider ECC video stack if needed. Use when the user wants a clean animated explainer rather than a generic talking-head script.

DevelopmentClaude

laravel-plugin-discovery

144923
from affaan-m/everything-claude-code

Discover and evaluate Laravel packages via LaraPlugins.io MCP. Use when the user wants to find plugins, check package health, or assess Laravel/PHP compatibility.

DevelopmentClaude

design-system

144923
from affaan-m/everything-claude-code

Use this skill to generate or audit design systems, check visual consistency, and review PRs that touch styling.

DevelopmentClaude

click-path-audit

144923
from affaan-m/everything-claude-code

Trace every user-facing button/touchpoint through its full state change sequence to find bugs where functions individually work but cancel each other out, produce wrong final state, or leave the UI in an inconsistent state. Use when: systematic debugging found no bugs but users report broken buttons, or after any major refactor touching shared state stores.

DevelopmentClaude

ck

144923
from affaan-m/everything-claude-code

Persistent per-project memory for Claude Code. Auto-loads project context on session start, tracks sessions with git activity, and writes to native memory. Commands run deterministic Node.js scripts — behavior is consistent across model versions.

DevelopmentClaude