
关于
Spring Boot 项目的验证循环:构建、静态分析、带覆盖率的测试、安全扫描和发布或 PR 前的差异审查。
name: springboot-verification description: "Spring Boot项目的验证循环:构建、静态分析、带覆盖率的测试、安全扫描和发布或PR前的差异审查。" origin: ECC
Spring Boot验证循环
在PR之前、重大变更之后和部署前运行。
何时激活
- 在为Spring Boot服务打开拉取请求之前
- 在重大重构或依赖升级之后
- 预部署验证(暂存或生产环境)
- 运行完整的构建 → 检查 → 测试 → 安全扫描管线
- 验证测试覆盖率是否达到阈值
阶段1:构建
mvn -T 4 clean verify -DskipTests
# or
./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 # verify 80%+ coverage
# or
./gradlew test jacocoTestReport
报告:
- 总测试数、通过/失败
- 覆盖率%(行/分支)
单元测试
使用模拟依赖隔离测试服务逻辑:
@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上下文测试控制器层:
@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:安全扫描
# Dependency CVEs
mvn org.owasp:dependency-check-maven:check
# or
./gradlew dependencyCheckAnalyze
# Secrets in source
grep -rn "password\s*=\s*\"" src/ --include="*.java" --include="*.yml" --include="*.properties"
grep -rn "sk-\|api_key\|secret" src/ --include="*.java" --include="*.yml"
# Secrets (git history)
git secrets --scan # if configured
常见安全发现
# Check for System.out.println (use logger instead)
grep -rn "System\.out\.print" src/main/ --include="*.java"
# Check for raw exception messages in responses
grep -rn "e\.getMessage()" src/main/ --include="*.java"
# Check for wildcard CORS
grep -rn "allowedOrigins.*\*" src/main/ --include="*.java"
阶段5:代码检查/格式化(可选门控)
mvn spotless:apply # if using Spotless plugin
./gradlew spotlessApply
阶段6:差异审查
git diff --stat
git diff
兼容工具
Claude CodeCursor
标签
测试

