
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 suites for Spring Boot applications.
- Installs
- 4.3K
- Last 24h
- +9
- Trending rank
- #9112
- Security
- Warn
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-test-patterns- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads spring-boot-test-patterns automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
Security audits
Independent scans of the skill's instructions and bundled files.
SKILL.md
The instructions your agent reads when the skill is triggered.
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
@WebMvcTestor MockMvc - Configuring
@ServiceConnectionfor 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
- Unit Tests — Fast, isolated tests without Spring context (< 50ms)
- Slice Tests — Minimal Spring context for specific layers (< 100ms)
- 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:
@DataJpaTestfor repositories,@WebMvcTestfor controllers,@SpringBootTestonly for full integration - Prefer
@ServiceConnectionon 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
@DirtiesContextunless absolutely necessary (forces context rebuild) - Avoid mixing
@MockBeanwith 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
@SpringBootTestfor unit tests; use plain Mockito instead - Context caching can be invalidated by different
@MockBeanconfigurations - Avoid static mutable state in tests (causes flaky tests)
References
- test-dependencies.md — Maven/Gradle test dependencies
- unit-testing.md — Unit testing with Mockito patterns
- slice-testing.md — Repository, controller, and JSON slice tests
- testcontainers-setup.md — Testcontainers configuration patterns
- ci-cd-configuration.md — GitHub Actions, GitLab CI, Docker Compose
- api-reference.md — Complete test annotations and utilities
- best-practices.md — Testing patterns and optimization
- workflow-patterns.md — Complete integration test examples
FAQ
What does the spring-boot-test-patterns skill do?
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.
How do I install spring-boot-test-patterns?
Run npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill spring-boot-test-patterns in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/spring-boot-test-patterns/ (personal) or .claude/skills/spring-boot-test-patterns/ (project).
Which AI agents can use spring-boot-test-patterns?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is spring-boot-test-patterns safe to install?
Security partners have reviewed it: Gen Agent Trust Hub passed; Socket passed; Snyk passed; Runlayer flagged items to review; ZeroLeaks passed. As with any skill, read the SKILL.md and bundled scripts before installing.
Who maintains spring-boot-test-patterns?
It is published by giuseppe-trisciuoglio in giuseppe-trisciuoglio/developer-kit. It has 4,280 recorded installs.
More from giuseppe-trisciuoglio/developer-kit
shadcn-ui
giuseppe-trisciuoglio/developer-kit
Provides complete shadcn/ui component library patterns including installation, configuration, and implementation of accessible React components. Use when setting up shadcn/ui, installing components, building forms with React Hook Form and Zod, customizing themes with Tailwind CSS, or implementing UI patterns like buttons, dialogs, dropdowns, tables, and complex form layouts.
tailwind-css-patterns
giuseppe-trisciuoglio/developer-kit
Provides comprehensive Tailwind CSS utility-first styling patterns including responsive design, layout utilities, flexbox, grid, spacing, typography, colors, and modern CSS best practices. Use when styling React/Vue/Svelte components, building responsive layouts, implementing design systems, or optimizing CSS workflow.
drizzle-orm-patterns
giuseppe-trisciuoglio/developer-kit
Provides comprehensive Drizzle ORM patterns for schema definition, CRUD operations, relations, queries, transactions, and migrations. Proactively use for any Drizzle ORM development including defining database schemas, writing type-safe queries, implementing relations, managing transactions, and setting up migrations with Drizzle Kit. Supports PostgreSQL, MySQL, SQLite, MSSQL, and CockroachDB.
unit-test-bean-validation
giuseppe-trisciuoglio/developer-kit
Provides patterns for unit testing Jakarta Bean Validation (JSR-380), including @Valid, @NotNull, @Min, @Max, @Email constraints with Hibernate Validator. Generates custom validator tests, constraint violation assertions, validation groups, and parameterized validation tests. Validates data integrity logic without Spring context. Use when writing validation tests, bean validation tests, or testing custom constraint validators.
nextjs-performance
giuseppe-trisciuoglio/developer-kit
Expert Next.js performance optimization skill covering Core Web Vitals, image/font optimization, caching strategies, streaming, bundle optimization, and Server Components best practices. Use when optimizing Next.js applications for Core Web Vitals (LCP, INP, CLS), implementing next/image and next/font, configuring caching with unstablecache and revalidateTag, converting Client Components to Server Components, implementing Suspense streaming, or analyzing and reducing bundle size. Supports Next.js 16 + React 19 patterns.
react-patterns
giuseppe-trisciuoglio/developer-kit
Provides comprehensive React 19 patterns for Server Components, Server Actions, useOptimistic, useActionState, useTransition, concurrent features, Suspense boundaries, and TypeScript integration. Generates executable code patterns, validates security for public endpoints, and optimizes performance with React Compiler or manual memoization. Proactively use when building React 19 applications with Next.js App Router, implementing optimistic UI, or optimizing concurrent rendering.
Popular testing & qa skills
tdd
mattpocock/skills
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
grilling
mattpocock/skills
Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
migrate-to-shoehorn
mattpocock/skills
Migrate test files from as type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace as in tests, or needs partial test data.
run-train
lllllllama/rigorpilot-skills
Rigor Train skill for deep learning research repositories. Use when a documented or selected training command should be run conservatively for startup verification, short-run verification, full kickoff, or resume, with command, config, seed, log, checkpoint, status, and metric evidence written to standardized trainoutputs/. Do not use for environment setup, exploratory sweeps, speculative idea implementation, or end-to-end orchestration.
test-driven-development
obra/superpowers
Use when implementing any feature or bugfix, before writing implementation code
finishing-a-development-branch
obra/superpowers
Use when implementation is complete, all tests pass, and you need to decide how to integrate the work