---
name: springboot-tdd-fa1fc5e1b0c9
description: 使用 JUnit 5, Mockito, MockMvc, Testcontainers 和 JaCoCo 进行 Spring Boot 的测试驱动开发（TDD）。适用于添加新功能、修复 bug 或重构场景。
---

# Spring Boot TDD 工作流 (Spring Boot TDD Workflow)

为 Spring Boot 服务提供测试驱动开发（TDD）指南，要求覆盖率达到 80% 以上（单元测试 + 集成测试）。

## 何时使用

- 新功能或新端点（Endpoint）
- Bug 修复或重构
- 添加数据访问逻辑或安全规则

## 工作流 (Workflow)

1) 先写测试（且测试应当失败）
2) 实现能让测试通过的最小化代码
3) 在保持测试通过（Green）的状态下进行重构
4) 强制执行覆盖率检查（JaCoCo）

## 单元测试 (Unit Testing - 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 (准备-执行-断言)
- 避免使用部分 Mock（Partial Mock），优先使用显式打桩（Stubbing）
- 针对多种变体情况使用 `@ParameterizedTest`

## Web 层测试 (Web Layer Testing - 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());
  }
}
```

## 集成测试 (Integration Testing - 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());
  }
}
```

## 持久化测试 (Persistence Testing - 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 上下文 (Context)

## 覆盖率 (Coverage - 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>
```

## 断言 (Assertions)

- 为了可读性，优先使用 AssertJ (`assertThat`)
- 对于 JSON 响应使用 `jsonPath`
- 对于异常：`assertThatThrownBy(...)`

## 测试数据生成器 (Test Data Builder)

```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 命令 (CI Commands)

- Maven: `mvn -T 4 test` 或 `mvn verify`
- Gradle: `./gradlew test jacocoTestReport`

**请记住**：保持测试的高速、隔离和确定性。测试行为而非实现细节。


---
Source attribution: xu-xiang
Original project: https://github.com/xu-xiang/everything-claude-code-zh/blob/dfbf9467b90dfd29bffa842c4e0a6977112900e2/docs/ja-JP/skills/springboot-tdd/SKILL.md
License: MIT
License information: https://opensource.org/license/mit
Original upstream instructions; downloaded from Mega AI Hub.

## Upstream license notice

MIT License

Copyright (c) 2026 Affaan Mustafa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.



# Mega AI Hub resource metadata

Creator / publisher: xu-xiang
Original project: https://github.com/xu-xiang/everything-claude-code-zh/blob/dfbf9467b90dfd29bffa842c4e0a6977112900e2/docs/ja-JP/skills/springboot-tdd/SKILL.md
Attribution basis: Source repository record

Fields of work: Development & Engineering
Roles: Backend Developer, DevOps / SRE, QA / Test Engineer
Specialties: Backend, Testing
Tools: Junit, Jacoco, Mockmvc, Mockito, Testcontainers
Country applicability: Country not specified
Classification basis: Source catalog labels
Instruction SHA-256: 2374e333ed25fe139ad1b28f2283550419aa59ab6228e9c0248da2fcdf68e806
