/spring-boot-test-patterns
Provides comprehensive testing patterns for Spring Boot applications covering unit, integration, slice, and container-based testing with JUnit 5, Mockito, Testcontainers, and performance optimization. Use when writing tests, @Test methods, @MockBean mocks, or implementing test
$ npx -y skills add giuseppe-trisciuoglio/developer-kit --skill spring-boot-test-patterns --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
- Fires itselfAuto-invocation. Claude auto-loads it when your prompt matches the work.
- You can call itInvoke it directly when you want it.
- Slash command
/spring-boot-test-patterns
Context preview
The summary Claude sees to decide when to auto-load this skill.
Provides comprehensive testing patterns for Spring Boot applications covering unit, integration, slice, and container-based testing with JUnit 5, Mockito, Testcontainers, and performance optimization. Use when writing tests, @Test methods, @MockBean mocks, or implementing test
SKILL.md
spring-boot-test-patterns.SKILL.mdname: spring-boot-test-patterns
description: Provides comprehensive testing patterns for Spring Boot applications covering unit, integration, slice, and container-based testing with JUnit 5, Mockito, Testcontainers, and performance optimization. Use when writing tests, @Test methods, @MockBean mocks, or implementing test suites for Spring Boot applications.
allowed-tools: Read, Write, Edit, Bash, Glob, Grep
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 Type | Annotation | Target Time | Use Case | |-----------|------------|-------------|----------| | **Unit Tests** | `@ExtendWith(MockitoExtension.class)` | < 50ms | Business logic without Spring context | | **Repository Tests** | `@DataJpaTest` | < 100ms | Database operations with minimal context | | **Controller Tests** | `@WebMvcTest` / `@WebFluxTest` | < 100ms | REST API layer testing | | **Integration Tests** | `@SpringBootTest` | < 500ms | Full application context with containers | | **Testcontainers** | `@ServiceConnection` / `@Testcontainers` | Varies | Real 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](references/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](references/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](references/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](references/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 testSee [ci-cd-configuration.md](references/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
priRead more
name: spring-boot-test-patterns description: Provides comprehensive testing patterns for Spring Boot applications covering unit, integration, slice, and container-based testing with JUnit 5, Mockito, Testcontainers, and performance optimization. Use when writing tests, @Test methods, @MockBean mocks, or implementing test suites for Spring Boot applications. allowed-tools: Read, Write, Edit, Bash, Glob, Grep
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 Type | Annotation | Target Time | Use Case | |-----------|------------|-------------|----------| | **Unit Tests** | `@ExtendWith(MockitoExtension.class)` | < 50ms | Business logic without Spring context | | **Repository Tests** | `@DataJpaTest` | < 100ms | Database operations with minimal context | | **Controller Tests** | `@WebMvcTest` / `@WebFluxTest` | < 100ms | REST API layer testing | | **Integration Tests** | `@SpringBootTest` | < 500ms | Full application context with containers | | **Testcontainers** | `@ServiceConnection` / `@Testcontainers` | Varies | Real 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](references/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](references/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](references/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](references/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 testSee [ci-cd-configuration.md](references/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
priShowing the first part of this file.
Modular plugin marketplace for Claude Code and agentic CLIs, with validated, spec-driven skills, agents, commands, and workflows for Java, TypeScript, Python, PHP, AWS, and AI.
Repo: giuseppe-trisciuoglio/developer-kit
Other skills on developer-kit.
- /chunking-strategy
Provides chunking strategies for RAG systems. Generates chunk size recommendations (256-1024 tokens), overlap percentages (10-20%), and semantic boundary detection methods. Validates semantic coherence and evaluates retrieval precision/recall metrics. Use when building
Open skill - /prompt-engineering
Provides workflows to write, debug, and optimize prompts for LLMs, including few-shot example selection, chain-of-thought structuring, system prompt design, and template composition. Use when the user asks to write or improve a prompt, wants help with few-shot examples,
Open skill - /rag
Implements document chunking, embedding generation, vector storage, and retrieval pipelines for Retrieval-Augmented Generation systems. Use when building RAG applications, creating document Q&A systems, or integrating AI with knowledge bases.
Open skill - /aws-cloudformation-auto-scaling
Provides AWS CloudFormation patterns for Auto Scaling including EC2, ECS, and Lambda. Use when creating Auto Scaling groups, launch configurations, launch templates, scaling policies, lifecycle hooks, and predictive scaling. Covers template structure with Parameters, Outputs,
Open skill - /aws-cloudformation-bedrock
Provides AWS CloudFormation patterns for Amazon Bedrock resources including agents, knowledge bases, data sources, guardrails, prompts, flows, and inference profiles. Use when creating Bedrock agents with action groups, implementing RAG with knowledge bases, configuring vector
Open skill - /aws-cloudformation-cloudfront
Provides AWS CloudFormation patterns for CloudFront distributions, origins (ALB, S3, Lambda@Edge, VPC Origins), CacheBehaviors, Functions, SecurityHeaders, parameters, Outputs and cross-stack references. Use when creating CloudFront distributions with CloudFormation, configuring
Open skill

