springboot-verification

springboot-verification

熱門

Spring Boot 專案的驗證循環:建置、靜態分析、含覆蓋率的測試、安全掃描,以及在發佈或 PR 前進行差異審查。

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

Spring Boot 專案的驗證循環:建置、靜態分析、含覆蓋率的測試、安全掃描,以及在發佈或 PR 前進行差異審查。

Spring Boot 驗證循環

在 PR 前、重大變更後以及部署前執行。

何時啟用

  • 在為 Spring Boot 服務開啟 pull request 之前
  • 在重大重構或相依套件升級之後
  • 預備部署至 staging 或 production 前的驗證
  • 執行完整建置 → lint → 測試 → 安全掃描流程
  • 驗證測試覆蓋率是否達到門檻

階段 1:建置

mvn -T 4 clean verify -DskipTests
# 或
./gradlew clean assemble -x test

如果建置失敗,請停止並修正。

階段 2:靜態分析

Maven(常用外掛):

mvn -T 4 spotbugs:check pmd:check checkstyle:check

Gradle(如有設定):

./gradlew checkstyleMain pmdMain spotbugsMain

階段 3:測試 + 覆蓋率

mvn -T 4 test
mvn jacoco:report   # 驗證 80% 以上覆蓋率
# 或
./gradlew test jacocoTestReport

報告:

  • 總測試數、通過/失敗
  • 覆蓋率 %(行/分支)

單元測試

使用 mock 的相依性隔離測試服務邏輯:

@ExtendWith(MockitoExtension.class)
class UserServiceTest {

  @Mock private UserRepository userRepository;
  @InjectMocks private UserService userService;

  @Test
  void createUser_validInput_returnsUser() {
    var dto = new CreateUserDto("Alice", "alice@example.com");
    var expected = new User(1L, "Alice", "alice@example.com");
    when(userRepository.save(any(User.class))).thenReturn(expected);

    var result = userService.create(dto);

    assertThat(result.name()).isEqualTo("Alice");
    verify(userRepository).save(any(User.class));
  }

  @Test
  void createUser_duplicateEmail_throwsException() {
    var dto = new CreateUserDto("Alice", "existing@example.com");
    when(userRepository.existsByEmail(dto.email())).thenReturn(true);

    assertThatThrownBy(() -> userService.create(dto))
        .isInstanceOf(DuplicateEmailException.class);
  }
}

使用 Testcontainers 的整合測試

針對真實資料庫而非 H2 進行測試:

@SpringBootTest
@Testcontainers
class UserRepositoryIntegrationTest {

  @Container
  static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16-alpine")
      .withDatabaseName("testdb");

  @DynamicPropertySource
  static void configureProperties(DynamicPropertyRegistry registry) {
    registry.add("spring.datasource.url", postgres::getJdbcUrl);
    registry.add("spring.datasource.username", postgres::getUsername);
    registry.add("spring.datasource.password", postgres::getPassword);
  }

  @Autowired private UserRepository userRepository;

  @Test
  void findByEmail_existingUser_returnsUser() {
    userRepository.save(new User("Alice", "alice@example.com"));

    var found = userRepository.findByEmail("alice@example.com");

    assertThat(found).isPresent();
    assertThat(found.get().getName()).isEqualTo("Alice");
  }
}

使用 MockMvc 的 API 測試

在完整的 Spring 上下文中測試 Controller 層:

@WebMvcTest(UserController.class)
class UserControllerTest {

  @Autowired private MockMvc mockMvc;
  @MockBean private UserService userService;

  @Test
  void createUser_validInput_returns201() throws Exception {
    var user = new UserDto(1L, "Alice", "alice@example.com");
    when(userService.create(any())).thenReturn(user);

    mockMvc.perform(post("/api/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""
                {"name": "Alice", "email": "alice@example.com"}
                """))
        .andExpect(status().isCreated())
        .andExpect(jsonPath("$.name").value("Alice"));
  }

  @Test
  void createUser_invalidEmail_returns400() throws Exception {
    mockMvc.perform(post("/api/users")
            .contentType(MediaType.APPLICATION_JSON)
            .content("""
                {"name": "Alice", "email": "not-an-email"}
                """))
        .andExpect(status().isBadRequest());
  }
}

階段 4:安全掃描

# 相依套件 CVE
mvn org.owasp:dependency-check-maven:check
# 或
./gradlew dependencyCheckAnalyze

# 原始碼中的機密資訊
grep -rn "password\s*=\s*\"" src/ --include="*.java" --include="*.yml" --include="*.properties"
grep -rn "sk-\|api_key\|secret" src/ --include="*.java" --include="*.yml"

# 機密資訊(git 歷史)
git secrets --scan  # 如有設定

常見安全發現

# 檢查 System.out.println(應使用 logger)
grep -rn "System\.out\.print" src/main/ --include="*.java"

# 檢查回應中是否包含原始例外訊息
grep -rn "e\.getMessage()" src/main/ --include="*.java"

# 檢查是否使用萬用字元 CORS
grep -rn "allowedOrigins.*\*" src/main/ --include="*.java"

階段 5:Lint/格式化(選擇性關卡)

mvn spotless:apply   # 如果使用 Spotless 外掛
./gradlew spotlessApply

階段 6:差異審查

git diff --stat
git diff

檢查清單:

  • 沒有遺留的除錯日誌(System.outlog.debug 未加保護)
  • 有意義的錯誤訊息和 HTTP 狀態碼
  • 必要時有交易和驗證
  • 設定變更有文件記錄

輸出範本

VERIFICATION REPORT
===================
Build:     [PASS/FAIL]
Static:    [PASS/FAIL] (spotbugs/pmd/checkstyle)
Tests:     [PASS/FAIL] (X/Y passed, Z% coverage)
Security:  [PASS/FAIL] (CVE findings: N)
Diff:      [X files changed]

Overall:   [READY / NOT READY]

Issues to Fix:
1. ...
2. ...

持續模式

  • 在重大變更後或長時間工作階段中每 30–60 分鐘重新執行各階段
  • 保持短循環:mvn -T 4 test + spotbugs 以獲得快速回饋

切記:快速回饋勝過後期的意外。嚴格把關——在正式環境中將警告視為缺陷。