---
id: daily-spring-boot-testing
name: "spring-boot-testing"
url: https://skills.yangsir.net/skill/daily-spring-boot-testing
author: github
domain: testing
tags: ["testing", "spring-boot", "java", "integration-testing", "unit-testing"]
install_count: 2000
rating: 4.30 (20 reviews)
github: https://github.com/github/awesome-copilot
---

# spring-boot-testing

> 提供 Spring Boot 应用测试指南，涵盖单元测试、集成测试和测试切片的最佳实践

**Stats**: 2,000 installs · 4.3/5 (20 reviews)

## Before / After 对比

### 优化测试切片选择

**Before**:

在没有 `spring-boot-testing` 技能指导的情况下，Spring Boot 开发者在编写测试时，常因不熟悉测试金字塔原则和各种测试切片（Test Slice）的适用场景，而倾向于过度使用 `@SpringBootTest`。这意味着即使是针对单个控制器或数据仓库的测试，也需要加载完整的应用上下文，导致测试启动缓慢、执行时间长，并消耗更多系统资源。开发者可能需要花费额外的时间手动配置或模拟不必要的依赖，增加了测试代码的复杂性和维护成本，降低了开发效率。

**After**:

借助 `spring-boot-testing` 技能，开发者能够遵循“测试金字塔”和“选择最窄切片”的原则，根据具体场景（如控制器、数据仓库、REST 客户端）快速定位并应用最合适的测试切片注解，例如 `@WebMvcTest`、`@DataJpaTest` 或 `@RestClientTest`。这确保了测试只加载所需的最少组件，显著缩短了测试的启动和执行时间，降低了资源消耗。同时，技能提供的最佳实践简化了测试配置和依赖管理，提高了测试的效率和可靠性。

| Metric | Before | After | Change |
|---|---|---|---|
| 单个测试执行时间 | 8秒 | 1.5秒 | -81.25% |
| 测试资源消耗 (内存) | 500MB | 150MB | -70% |
| 测试配置代码量 | 20行 | 8行 | -60% |

### 提升测试代码可读性与效率

**Before**:

在缺乏 `spring-boot-testing` 技能的指导下，开发者在编写 Spring Boot Web 层测试时，可能仍沿用传统的 `MockMvc` 语法，例如通过链式调用 `andExpect()` 方法来验证响应。这种方式虽然有效，但可能导致测试代码冗长且不够流畅。同时，如果未使用 AssertJ 等现代断言库，断言语句会显得分散和不够直观，降低了测试代码的可读性和维护性。开发者需要花费更多精力来理解和编写复杂的 HTTP 响应验证逻辑。

**After**:

通过 `spring-boot-testing` 技能的指引，开发者能够采纳现代化的 `MockMvcTester` 和 `RestTestClient` API，并结合 `AssertJ Style` 的流畅断言。这使得 Web 层测试代码变得极其简洁和富有表现力。例如，使用 `MockMvcTester` 可以将多个断言整合到单个链式调用中，极大地提升了代码的可读性和编写效率。这种现代化的方法减少了样板代码，使测试意图一目了然，从而加速了测试开发过程并降低了长期维护成本。

| Metric | Before | After | Change |
|---|---|---|---|
| 单个Web层测试代码行数 | 30行 | 15行 | -50% |
| 测试代码理解时间 | 60秒 | 20秒 | -66.67% |
| 编写测试时间 | 15分钟 | 8分钟 | -46.67% |

## Readme

# spring-boot-testing

# Spring Boot Testing

This skill provides expert guide for testing Spring Boot 4 applications with modern patterns and best practices.

## Core Principles

- **Test Pyramid**: Unit (fast) > Slice (focused) > Integration (complete)

- **Right Tool**: Use the narrowest slice that gives you confidence

- **AssertJ Style**: Fluent, readable assertions over verbose matchers

- **Modern APIs**: Prefer MockMvcTester and RestTestClient over legacy alternatives

## Which Test Slice?

Scenario
Annotation
Reference

Controller + HTTP semantics
`@WebMvcTest`
[references/webmvctest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/webmvctest.md)

Repository + JPA queries
`@DataJpaTest`
[references/datajpatest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/datajpatest.md)

REST client + external APIs
`@RestClientTest`
[references/restclienttest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/restclienttest.md)

JSON (de)serialization
`@JsonTest`
[references/test-slices-overview.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/test-slices-overview.md)

Full application
`@SpringBootTest`
[references/test-slices-overview.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/test-slices-overview.md)

## Test Slices Reference

- [references/test-slices-overview.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/test-slices-overview.md) - Decision matrix and comparison

- [references/webmvctest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/webmvctest.md) - Web layer with MockMvc

- [references/datajpatest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/datajpatest.md) - Data layer with Testcontainers

- [references/restclienttest.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/restclienttest.md) - REST client testing

## Testing Tools Reference

- [references/mockmvc-tester.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/mockmvc-tester.md) - AssertJ-style MockMvc (3.2+)

- [references/mockmvc-classic.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/mockmvc-classic.md) - Traditional MockMvc (pre-3.2)

- [references/resttestclient.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/resttestclient.md) - Spring Boot 4+ REST client

- [references/mockitobean.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/mockitobean.md) - Mocking dependencies

## Assertion Libraries

- [references/assertj-basics.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/assertj-basics.md) - Scalars, strings, booleans, dates

- [references/assertj-collections.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/assertj-collections.md) - Lists, Sets, Maps, arrays

## Testcontainers

- [references/testcontainers-jdbc.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/testcontainers-jdbc.md) - PostgreSQL, MySQL, etc.

## Test Data Generation

- [references/instancio.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/instancio.md) - Generate complex test objects (3+ properties)

## Performance & Migration

- [references/context-caching.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/context-caching.md) - Speed up test suites

- [references/sb4-migration.md](https://github.com/github/awesome-copilot/blob/HEAD/skills/spring-boot-testing/references/sb4-migration.md) - Spring Boot 4.0 changes

## Quick Decision Tree

```
Testing a controller endpoint?
  Yes → @WebMvcTest with MockMvcTester

Testing repository queries?
  Yes → @DataJpaTest with Testcontainers (real DB)

Testing business logic in service?
  Yes → Plain JUnit + Mockito (no Spring context)

Testing external API client?
  Yes → @RestClientTest with MockRestServiceServer

Testing JSON mapping?
  Yes → @JsonTest

Need full integration test?
  Yes → @SpringBootTest with minimal context config

```

## Spring Boot 4 Highlights

- **RestTestClient**: Modern alternative to TestRestTemplate

- **@MockitoBean**: Replaces @MockBean (deprecated)

- **MockMvcTester**: AssertJ-style assertions for web tests

- **Modular starters**: Technology-specific test starters

- **Context pausing**: Automatic pausing of cached contexts (Spring Framework 7)

## Testing Best Practices

### Code Complexity Assessment

When a method or class is too complex to test effectively:

- **Analyze complexity** - If you need more than 5-7 test cases to cover a single method, it's likely too complex

- **Recommend refactoring** - Suggest breaking the code into smaller, focused functions

- **User decision** - If the user agrees to refactor, help identify extraction points

- **Proceed if needed** - If the user decides to continue with the complex code, implement tests despite the difficulty

**Example of refactoring recommendation:**

```
// Before: Complex method hard to test
public Order processOrder(OrderRequest request) {
  // Validation, discount calculation, payment, inventory, notification...
  // 50+ lines of mixed concerns
}

// After: Refactored into testable units
public Order processOrder(OrderRequest request) {
  validateOrder(request);
  var order = createOrder(request);
  applyDiscount(order);
  processPayment(order);
  updateInventory(order);
  sendNotification(order);
  return order;
}

```

### Avoid Code Redundancy

Create helper methods for commonly used objects and mock setup to enhance readability and maintainability.

### Test Organization with @DisplayName

Use descriptive display names to clarify test intent:

```
@Test
@DisplayName("Should calculate discount for VIP customer")
void shouldCalculateDiscountForVip() { }

@Test
@DisplayName("Should reject order when customer has insufficient credit")
void shouldRejectOrderForInsufficientCredit() { }

```

### Test Coverage Order

Always structure tests in this order:

- **Main scenario** - The happy path, most common use case

- **Other paths** - Alternative valid scenarios, edge cases

- **Exceptions/Errors** - Invalid inputs, error conditions, failure modes

### Test Production Scenarios

Write tests with real production scenarios in mind. This makes tests more relatable and helps understand code behavior in actual production cases.

### Test Coverage Goals

Aim for 80% code coverage as a practical balance between quality and effort. Higher coverage is beneficial but not the only goal.

Use Jacoco maven plugin for coverage reporting and tracking.

**Coverage Rules:**

- 80+% coverage minimum

- Focus on meaningful assertions, not just execution

**What to Prioritize:**

- Business-critical paths (payment processing, order validation)

- Complex algorithms (pricing, discount calculations)

- Error handling (exceptions, edge cases)

- Integration points (external APIs, databases)

## Dependencies (Spring Boot 4)

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

<!-- For WebMvc tests -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-webmvc-test</artifactId>
  <scope>test</scope>
</dependency>

<!-- For Testcontainers -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-testcontainers</artifactId>
  <scope>test</scope>
</dependency>

```
Weekly Installs297Repository[github/awesome-copilot](https://github.com/github/awesome-copilot)GitHub Stars27.4KFirst Seen9 days agoSecurity Audits[Gen Agent Trust HubPass](/github/awesome-copilot/spring-boot-testing/security/agent-trust-hub)[SocketPass](/github/awesome-copilot/spring-boot-testing/security/socket)[SnykPass](/github/awesome-copilot/spring-boot-testing/security/snyk)Installed ongemini-cli273opencode272codex272cursor269github-copilot268kimi-cli267

---
*Source: https://skills.yangsir.net/skill/daily-spring-boot-testing*
*Markdown mirror: https://skills.yangsir.net/api/skill/daily-spring-boot-testing/markdown*