Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

spring-boot-test-patternsSpring Boot 测试模式

Agent Skill

用于辅助 Java 项目开发、面向对象设计、Spring 生态、Maven 或 Gradle 依赖和后端工程实践。它适合让 Agent 分析类结构、设计接口、整理服务分层、生成测试或检查常见代码坏味道。使用时需要结合项目已有架构、包结构和依赖版本,不应只按通用教程改代码;涉及数据库、事务、并发或框架配置时,应先确认运行环境和回归测试范围。

总安装

22,448

周安装

917

GitHub Stars

229

下载量

7,263
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:spring-boot-test-patterns(Spring Boot 测试模式)
来源仓库:https://github.com/giuseppe-trisciuoglio/developer-kit
仓库路径:skills/spring-boot-test-patterns
安装命令:
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-test-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-test-patterns

简介

Spring Boot 应用程序的综合测试模式涵盖单元、切片、集成和基于容器的测试。

  • 涵盖四种具有性能目标的测试类型:单元测试(< 50ms)、切片测试(< 100ms)、集成测试(< 500ms)以及使用测试容器的完整上下文测试
  • 包括基于 Mockito 的单元测试、使用重点 Spring 上下文的 JPA/MVC 切片测试以及使用 MockMvc 和 WebTestClient 进行 REST API 测试的模式
  • 演示 Spring Boot 3.5+ @ServiceConnection
  • 用于更清洁的容器管理和@DynamicPropertySource
  • 用于动态财产登记
  • 提供 GitHub Actions 和 Docker Compose 的上下文缓存策略、容器重用模式以及 CI/CD 配置示例

SKILL.md

Spring Boot Testing Patterns

Overview

Comprehensive guidance for writing robust test suites for Spring Boot applications using JUnit 5, Mockito, Testcontainers, and performance-optimized slice testing patterns.

When to Use

  • Writing unit tests for services or repositories with mocked dependencies
  • Implementing integration tests with real databases via Testcontainers
  • Testing REST APIs with @WebMvcTest or MockMvc
  • Configuring @ServiceConnection for container management in Spring Boot 3.5+

Quick Reference

Test TypeAnnotationTarget TimeUse Case
Unit Tests@ExtendWith(MockitoExtension.class)< 50msBusiness logic without Spring context
Repository Tests@DataJpaTest< 100msDatabase operations with minimal context
Controller Tests@WebMvcTest / @WebFluxTest< 100msREST API layer testing
Integration Tests@SpringBootTest< 500msFull application context with containers
Testcontainers@ServiceConnection / @TestcontainersVariesReal database/message broker containers

Core Concepts

Test Architecture Philosophy

  1. Unit Tests — Fast, isolated tests without Spring context (< 50ms)
  2. Slice Tests — Minimal Spring context for specific layers (< 100ms)
  3. Integration Tests — Full Spring context with real dependencies (< 500ms)

Key Annotations

Spring Boot Test:

  • @SpringBootTest — Full application context (use sparingly)
  • @DataJpaTest — JPA components only (repositories, entities)
  • @WebMvcTest — MVC layer only (controllers, @ControllerAdvice)
  • @WebFluxTest — WebFlux layer only (reactive controllers)
  • @JsonTest — JSON serialization components only

Testcontainers:

  • @ServiceConnection — Wire Testcontainer to Spring Boot (3.5+)
  • @DynamicPropertySource — Register dynamic properties at runtime
  • @Testcontainers — Enable Testcontainers lifecycle management

Instructions

1. Unit Testing Pattern

Test business logic with mocked dependencies:

@ExtendWith(MockitoExtension.class)
class UserServiceTest {
    @Mock
    private UserRepository userRepository;

    @InjectMocks
    private UserService userService;

    @Test
    void shouldFindUserByIdWhenExists() {
        when(userRepository.findById(1L)).thenReturn(Optional.of(user));
        Optional<User> result = userService.findById(1L);
        assertThat(result).isPresent();
        verify(userRepository).findById(1L);
    }
}

See unit-testing.md for advanced patterns.

2. Slice Testing Pattern

Use focused test slices for specific layers:

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestContainerConfig
class UserRepositoryIntegrationTest {
    @Autowired
    private UserRepository userRepository;

    @Test
    void shouldSaveAndRetrieveUser() {
        User saved = userRepository.save(user);
        assertThat(userRepository.findByEmail("test@example.com")).isPresent();
    }
}

See slice-testing.md for all slice patterns.

3. REST API Testing Pattern

Test controllers with MockMvc:

@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void shouldGetUserById() throws Exception {
        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.email").value("test@example.com"));
    }
}

4. Testcontainers with @ServiceConnection

Configure containers with Spring Boot 3.5+:

@TestConfiguration
public class TestContainerConfig {
    @Bean
    @ServiceConnection
    public PostgreSQLContainer<?> postgresContainer() {
        return new PostgreSQLContainer<>("postgres:16-alpine");
    }
}

Apply with @Import(TestContainerConfig.class) on test classes. See testcontainers-setup.md for detailed configuration.

5. Add Dependencies

Include required testing dependencies:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.testcontainers</groupId>
    <artifactId>junit-jupiter</artifactId>
    <version>1.19.0</version>
    <scope>test</scope>
</dependency>

See test-dependencies.md for complete dependency list.

6. Configure CI/CD

Set up GitHub Actions for automated testing:

name: Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    services:
      docker:
        image: docker:20-dind
    steps:
    - uses: actions/checkout@v4
    - name: Set up JDK 17
      uses: actions/setup-java@v4
      with:
        distribution: 'temurin'
    - name: Run tests
      run: ./mvnw test

See ci-cd-configuration.md for full CI/CD patterns.

Validation Checkpoints

After implementing tests, verify:

  • Container running: docker ps (look for testcontainer images)
  • Context loaded: check startup logs for "Started Application in X.XX seconds"
  • Test isolation: run tests individually and confirm no cross-contamination

Examples

Full Integration Test with @ServiceConnection

@SpringBootTest
@Import(TestContainerConfig.class)
class OrderServiceIntegrationTest {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserRepository userRepository;

    @Test
    void shouldCreateOrderForExistingUser() {
        User user = userRepository.save(User.builder()
            .email("order-test@example.com")
            .build());

        Order order = orderService.createOrder(user.getId(), List.of(
            new OrderItem("SKU-001", 2)
        ));

        assertThat(order.getId()).isNotNull();
        assertThat(order.getStatus()).isEqualTo(OrderStatus.PENDING);
    }
}

@DataJpaTest with Real Database

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestContainerConfig
class UserRepositoryTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    void shouldFindByEmail() {
        userRepository.save(User.builder()
            .email("jpa-test@example.com")
            .build());
        assertThat(userRepository.findByEmail("jpa-test@example.com"))
            .isPresent();
    }
}

See workflow-patterns.md for complete end-to-end examples.

Best Practices

  • Use the right test type: @DataJpaTest for repositories, @WebMvcTest for controllers, @SpringBootTest only for full integration
  • Prefer @ServiceConnection on Spring Boot 3.5+ for cleaner container management over @DynamicPropertySource
  • Keep tests deterministic: Initialize all test data explicitly in @BeforeEach
  • Organize by layer: Group tests by layer to maximize context caching
  • Reuse Testcontainers at JVM level (withReuse(true) + TESTCONTAINERS_REUSE_ENABLE=true)
  • Avoid @DirtiesContext: Forces context rebuild, significantly hurts performance
  • Mock external services, use real databases only when necessary
  • Performance targets: Unit < 50ms, Slice < 100ms, Integration < 500ms

Constraints and Warnings

  • Never use @DirtiesContext unless absolutely necessary (forces context rebuild)
  • Avoid mixing @MockBean with different configurations (creates separate contexts)
  • Testcontainers require Docker; ensure CI/CD pipelines have Docker support
  • Do not rely on test execution order; each test must be independent
  • Be cautious with @TestPropertySource (creates separate contexts)
  • Do not use @SpringBootTest for unit tests; use plain Mockito instead
  • Context caching can be invalidated by different @MockBean configurations
  • Avoid static mutable state in tests (causes flaky tests)

References

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

36.55%
按下载量换算2,655

Claude

29.27%
按下载量换算2,126

Cursor

20.64%
按下载量换算1,499

Gemini CLI

9.63%
按下载量换算699

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills