springboot-tdd

springboot-tdd

熱門

使用 JUnit 5、Mockito、MockMvc、Testcontainers 和 JaCoCo 進行 Spring Boot 的測試驅動開發。在新增功能、修復錯誤或重構時使用。

23萬星標
3.5萬分支
更新於 2026/7/14
SKILL.md
readonlyread-only
name
springboot-tdd
description

使用 JUnit 5、Mockito、MockMvc、Testcontainers 和 JaCoCo 進行 Spring Boot 的測試驅動開發。在新增功能、修復錯誤或重構時使用。

Spring Boot TDD 工作流程

針對 Spring Boot 服務的 TDD 指南,涵蓋 80% 以上的覆蓋率(單元測試 + 整合測試)。

使用時機

  • 新增功能或端點
  • 修復錯誤或重構
  • 新增資料存取邏輯或安全規則

工作流程

  1. 先撰寫測試(測試應失敗)
  2. 實作最少程式碼讓測試通過
  3. 在測試保持綠燈的情況下重構
  4. 強制覆蓋率(JaCoCo)

單元測試(JUnit 5 + Mockito)

@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
  • 避免部分模擬,優先使用明確的 stub
  • 使用 @ParameterizedTest 處理變體

Web 層測試(MockMvc)

@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)

@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)

@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 設定片段:

<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(...)

測試資料建構器

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 testmvn verify
  • Gradle:./gradlew test jacocoTestReport

切記:保持測試快速、隔離且確定性高。測試行為,而非實作細節。