SuperAPI AI Directory

springboot-verification

Testing & quality

View repository

Updated 10-16 04:39

About this skill

Spring Boot Verification Loop

Run before a pull request (PR), after major changes, and before deployment.

When to Trigger

  • Before opening a pull request for a Spring Boot service
  • After major refactoring or dependency upgrades
  • Verification before pre-release or production deployment
  • Run the full Build → Lint → Test → Security Scan pipeline
  • Verify whether test coverage meets the threshold

Phase 1: Build

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

If the build fails, stop and fix it.

Phase 2: Static Analysis

Maven (common plugins):

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

Gradle (if configured):

./gradlew checkstyleMain pmdMain spotbugsMain

Phase 3: Tests + Coverage

mvn -T 4 test
mvn jacoco:report   # 验证 80% 以上的覆盖率
# 或者
./gradlew test jacocoTestReport

Report contents:

  • Total tests, passed/failed count
  • Coverage % (line/branch)

Unit Tests

Test service logic in isolation with mocked dependencies:

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

Integration Tests with Testcontainers

Test against a real database instead of 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");
  }
}

API Tests with MockMvc

Test the controller layer in the full Spring context:

@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());
  }
}

Phase 4: Security Scan

# 依赖项 CVE 漏洞扫描
mvn org.owasp:dependency-check-maven:check
# 或者
./gradlew dependencyCheckAnalyze

# 源码中的密钥/敏感信息 (Secrets)
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  # 如果已配置

Common security issue checks

# 检查 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"

Phase 5: Lint/Format (optional gate)

mvn spotless:apply   # 如果使用了 Spotless 插件
./gradlew spotlessApply

Phase 6: Diff Review

git diff --stat
git diff

Checklist:

  • No leftover debug logs (System.out, unguarded log.debug)
  • Error messages and HTTP status codes are meaningful
  • Include transactions and validation where needed
  • Configuration changes are documented

Output Template

验证报告 (VERIFICATION REPORT)
===================
构建 (Build):     [通过/失败]
静态分析 (Static): [通过/失败] (spotbugs/pmd/checkstyle)
测试 (Tests):     [通过/失败] (X/Y 通过, Z% 覆盖率)
安全 (Security):  [通过/失败] (CVE 漏洞发现: N)
差异 (Diff):      [X 个文件已变更]

总体状态 (Overall): [准备就绪 / 尚未就绪]

待修复问题:
1. ...
2. ...

Continuous Mode

  • Re-run the phases on major changes, or every 30–60 minutes during long sessions.
  • Keep the loop short: run mvn -T 4 test + spotbugs for fast feedback.

Remember: Fast feedback is better than late "surprises". Keep the gate strict—in production systems, treat warnings as defects.