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

spring-boot-test弹簧启动测试

Agent Skill

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

总安装

1,162

周安装

47

GitHub Stars

12

下载量

365
CodexClaudeCursorGemini CLI

安装说明

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

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

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

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

命令行安装

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

skills.shnpx skills
npx skills add https://github.com/claude-dev-suite/claude-dev-suite --skill spring-boot-test

简介

用于 Spring Boot 应用各层级的自动化测试支持套件。

  • 适用于 Controller、Service 与 Repository 层的隔离测试。
  • 提供 MockMvc、Testcontainers 与 AssertJ 断言集成方案。
  • 测试数据库应使用独立实例避免污染生产数据。
  • 覆盖率达标后仍需补充边界条件与异常流测试用例。

SKILL.md

Spring Boot Testing

Deep Knowledge: Use mcp__documentation__fetch_docs with technology: spring-boot-test for comprehensive documentation.

When NOT to Use This Skill

  • Pure Unit Tests - Use junit with Mockito for faster tests without Spring context
  • Integration Tests with Real Database - Use spring-boot-integration with Testcontainers
  • REST API Client Testing - Use rest-assured for HTTP testing
  • E2E Web Testing - Use Selenium or Playwright
  • Microservice Contract Testing - Use Spring Cloud Contract

Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Includes: JUnit 5, Mockito, AssertJ, Hamcrest, JSONPath, Spring Test

Test Annotations

@SpringBootTest - Full Context

@SpringBootTest
class ApplicationTest {
    @Autowired
    private UserService userService;

    @Test
    void contextLoads() {
        assertThat(userService).isNotNull();
    }
}

// With web environment
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
class WebApplicationTest {
    @LocalServerPort
    private int port;

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    void healthCheck() {
        ResponseEntity<String> response = restTemplate
            .getForEntity("/actuator/health", String.class);
        assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
    }
}

Slice Tests (Faster, Focused)

AnnotationLayerAuto-configured
@WebMvcTestControllersMockMvc, Jackson
@DataJpaTestJPA RepositoriesTestEntityManager, DataSource
@DataMongoTestMongoDBMongoTemplate
@JsonTestJSON serializationJacksonTester
@RestClientTestREST clientsMockRestServiceServer
// Controller test - only loads web layer
@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void getUser_ReturnsUser() throws Exception {
        when(userService.findById(1L))
            .thenReturn(Optional.of(new User(1L, "John")));

        mockMvc.perform(get("/api/users/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.name").value("John"));
    }
}

// Repository test - uses embedded database
@DataJpaTest
class UserRepositoryTest {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private UserRepository repository;

    @Test
    void findByEmail_ReturnsUser() {
        User user = new User("test@example.com", "Test User");
        entityManager.persistAndFlush(user);

        Optional<User> found = repository.findByEmail("test@example.com");

        assertThat(found).isPresent()
            .hasValueSatisfying(u -> assertThat(u.getName()).isEqualTo("Test User"));
    }
}

MockMvc

Basic Requests

@WebMvcTest(UserController.class)
class UserControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    // GET request
    @Test
    void getUsers() throws Exception {
        when(userService.findAll()).thenReturn(List.of(
            new User(1L, "Alice"),
            new User(2L, "Bob")
        ));

        mockMvc.perform(get("/api/users")
                .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].name").value("Alice"));
    }

    // POST request with JSON body
    @Test
    void createUser() throws Exception {
        CreateUserRequest request = new CreateUserRequest("John", "john@example.com");
        User createdUser = new User(1L, "John", "john@example.com");

        when(userService.create(any())).thenReturn(createdUser);

        mockMvc.perform(post("/api/users")
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {
                        "name": "John",
                        "email": "john@example.com"
                    }
                    """))
            .andExpect(status().isCreated())
            .andExpect(header().exists("Location"))
            .andExpect(jsonPath("$.id").value(1));
    }

    // PUT request
    @Test
    void updateUser() throws Exception {
        mockMvc.perform(put("/api/users/{id}", 1)
                .contentType(MediaType.APPLICATION_JSON)
                .content("""
                    {"name": "Updated Name"}
                    """))
            .andExpect(status().isOk());

        verify(userService).update(eq(1L), any());
    }

    // DELETE request
    @Test
    void deleteUser() throws Exception {
        mockMvc.perform(delete("/api/users/{id}", 1))
            .andExpect(status().isNoContent());

        verify(userService).delete(1L);
    }
}

With Authentication

@WebMvcTest(AdminController.class)
@Import(SecurityConfig.class)
class AdminControllerTest {

    @Autowired
    private MockMvc mockMvc;

    // Using @WithMockUser
    @Test
    @WithMockUser(roles = "ADMIN")
    void adminEndpoint_WithAdminRole_Succeeds() throws Exception {
        mockMvc.perform(get("/api/admin/dashboard"))
            .andExpect(status().isOk());
    }

    @Test
    @WithMockUser(roles = "USER")
    void adminEndpoint_WithUserRole_Forbidden() throws Exception {
        mockMvc.perform(get("/api/admin/dashboard"))
            .andExpect(status().isForbidden());
    }

    // Using JWT token
    @Test
    void withJwtToken() throws Exception {
        String token = jwtTokenProvider.createToken("admin", List.of("ROLE_ADMIN"));

        mockMvc.perform(get("/api/admin/dashboard")
                .header("Authorization", "Bearer " + token))
            .andExpect(status().isOk());
    }
}

Mocking

@MockBean

@SpringBootTest
class OrderServiceTest {

    @Autowired
    private OrderService orderService;

    @MockBean  // Replaces bean in context with mock
    private PaymentGateway paymentGateway;

    @MockBean
    private InventoryService inventoryService;

    @Test
    void placeOrder_WhenPaymentSucceeds_CreatesOrder() {
        when(inventoryService.checkStock(any())).thenReturn(true);
        when(paymentGateway.charge(any())).thenReturn(PaymentResult.success());

        Order order = orderService.placeOrder(new OrderRequest(...));

        assertThat(order.getStatus()).isEqualTo(OrderStatus.CONFIRMED);
        verify(paymentGateway).charge(any());
    }

    @Test
    void placeOrder_WhenPaymentFails_ThrowsException() {
        when(paymentGateway.charge(any()))
            .thenThrow(new PaymentException("Card declined"));

        assertThatThrownBy(() -> orderService.placeOrder(new OrderRequest(...)))
            .isInstanceOf(PaymentException.class)
            .hasMessage("Card declined");
    }
}

@SpyBean

@SpringBootTest
class NotificationServiceTest {

    @Autowired
    private NotificationService notificationService;

    @SpyBean  // Wraps real bean, allows partial mocking
    private EmailSender emailSender;

    @Test
    void sendNotification_CallsEmailSender() {
        notificationService.notify(user, "Hello");

        verify(emailSender).send(eq(user.getEmail()), any());
    }

    @Test
    void sendNotification_WhenEmailFails_LogsError() {
        doThrow(new EmailException("SMTP error"))
            .when(emailSender).send(any(), any());

        // Method should handle exception gracefully
        assertThatCode(() -> notificationService.notify(user, "Hello"))
            .doesNotThrowAnyException();
    }
}

Test Configuration

Test Properties

@SpringBootTest
@TestPropertySource(properties = {
    "app.feature.enabled=true",
    "app.external.url=http://localhost:8080"
})
class FeatureTest { }

// Or use test profile
@SpringBootTest
@ActiveProfiles("test")
class ProfileTest { }

application-test.yml

spring:
  datasource:
    url: jdbc:h2:mem:testdb
    driver-class-name: org.h2.Driver
  jpa:
    hibernate:
      ddl-auto: create-drop

app:
  external:
    url: http://localhost:${wiremock.server.port}

Custom Test Configuration

@TestConfiguration
public class TestConfig {

    @Bean
    @Primary
    public Clock testClock() {
        return Clock.fixed(
            Instant.parse("2025-01-15T10:00:00Z"),
            ZoneId.of("UTC")
        );
    }

    @Bean
    @Primary
    public PaymentGateway testPaymentGateway() {
        return new FakePaymentGateway();
    }
}

@SpringBootTest
@Import(TestConfig.class)
class TimeBasedFeatureTest { }

AssertJ Assertions

// Basic assertions
assertThat(user.getName()).isEqualTo("John");
assertThat(user.getAge()).isGreaterThan(18);
assertThat(user.getEmail()).contains("@").endsWith(".com");

// Collection assertions
assertThat(users)
    .hasSize(3)
    .extracting(User::getName)
    .containsExactly("Alice", "Bob", "Charlie");

// Exception assertions
assertThatThrownBy(() -> service.process(null))
    .isInstanceOf(IllegalArgumentException.class)
    .hasMessageContaining("null");

// Optional assertions
assertThat(repository.findById(1L))
    .isPresent()
    .hasValueSatisfying(user ->
        assertThat(user.getName()).isEqualTo("John")
    );

// Soft assertions (collect all failures)
SoftAssertions.assertSoftly(softly -> {
    softly.assertThat(user.getName()).isEqualTo("John");
    softly.assertThat(user.getEmail()).contains("@");
    softly.assertThat(user.getAge()).isPositive();
});

Test Data Builders

public class UserTestBuilder {
    private Long id = 1L;
    private String name = "Test User";
    private String email = "test@example.com";
    private UserRole role = UserRole.USER;

    public static UserTestBuilder aUser() {
        return new UserTestBuilder();
    }

    public UserTestBuilder withId(Long id) {
        this.id = id;
        return this;
    }

    public UserTestBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public UserTestBuilder withEmail(String email) {
        this.email = email;
        return this;
    }

    public UserTestBuilder withRole(UserRole role) {
        this.role = role;
        return this;
    }

    public UserTestBuilder asAdmin() {
        this.role = UserRole.ADMIN;
        return this;
    }

    public User build() {
        return new User(id, name, email, role);
    }
}

// Usage
User admin = aUser().withName("Admin").asAdmin().build();
User regularUser = aUser().build();

Anti-Patterns

Anti-PatternWhy It's BadSolution
Using @SpringBootTest for all testsExtremely slowUse slice tests (@WebMvcTest, @DataJpaTest)
Not using @MockBeanTesting real beansMock external dependencies
Hardcoding ports in testsPort conflictsUse @LocalServerPort with RANDOM_PORT
Testing private methodsCoupled to implementationTest through controller/service API
Not isolating test dataTests interfereUse @Transactional or cleanup in @AfterEach
Ignoring @Sql scriptsManual setup duplicationUse @Sql for test data setup
No test profilesPolluting dev/prod configUse @ActiveProfiles("test")

Quick Troubleshooting

ProblemLikely CauseSolution
"Unable to find @SpringBootConfiguration"Main class not foundAdd @SpringBootTest(classes = App.class)
Test very slowUsing @SpringBootTest unnecessarilyUse slice tests (@WebMvcTest, etc.)
"No qualifying bean"Missing @MockBeanAdd @MockBean for dependencies
Port already in useHardcoded portUse webEnvironment = RANDOM_PORT
"Could not autowire"Bean not in test contextCheck component scan or add @Import
Flaky testDatabase state not resetUse @Transactional or @DirtiesContext

Reference

适合场景

01

用户想查找某类 Agent Skill 时

02

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

03

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

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

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

能力 4

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

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

平台分布

Codex

33.19%
按下载量换算121

Claude

29.25%
按下载量换算107

Cursor

17.44%
按下载量换算64

Gemini CLI

10.33%
按下载量换算38

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

敏感数据

该 Skill 可能接触密钥、Token、环境变量或敏感配置,应进入高风险复核队列,默认不自动发布。

安装前确认

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

来源信息

继续浏览同类 Skills