springboot-tdd

springboot-tdd

熱門

使用 JUnit 5、Mockito、MockMvc、Testcontainers 和 JaCoCo 進行 Spring Boot 的測試驅動開發 (TDD)。在新增功能、修復 Bug 或重構程式碼時使用。

24萬星標
3.6萬分支
更新於 2026/8/10
SKILL.md
唯讀
名稱
springboot-tdd
描述

使用 JUnit 5、Mockito、MockMvc、Testcontainers 和 JaCoCo 進行 Spring Boot 的測試驅動開發 (TDD)。在新增功能、修復 Bug 或重構程式碼時使用。

Spring Boot TDD 工作流程

針對 Spring Boot 服務的 TDD 指引,提供 80%+ 的測試涵蓋率(單元測試 + 整合測試)。

何時使用

  • 新增功能或 API 端點
  • 修復 Bug 或進行程式碼重構
  • 新增資料存取邏輯或安全性規則

工作流程

  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(安排-執行-斷言)
  • 避免使用 partial mock,優先使用明確的 stubbing
  • 針對多種測試案例使用 @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>

斷言 (Assertions)

  • 為了提升可讀性,優先使用 AssertJ (assertThat)
  • 針對 JSON 回應,使用 jsonPath
  • 針對例外狀況處理:使用 assertThatThrownBy(...)

測試資料建構器 (Test Data Builders)

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

請記住:保持測試快速、獨立且具確定性。測試的是「行為」,而非「實作細節」。