Spring Boot Testing
GitHubOfficialFirst committed by kartikdhimanDistributed by GitHub
- Skill
- Tool integration
- Software development
- MIT
- No issues found
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a comprehensive framework for testing Spring Boot applications, with a primary focus on Spring Boot 4 patterns while maintaining compatibility notes for version 3. It emphasizes the Test Pyramid, promoting the use of focused test slices over heavy integration tests. The guide covers modern testing tools like MockMvcTester, @MockitoBean, and Testcontainers, alongside best practices for test organization, coverage goals, and refactoring complex code for better testability.
What it does
- Provides a decision matrix for selecting the appropriate test slice (@WebMvcTest, @DataJpaTest, etc.)
- Outlines modern testing tool usage including @MockitoBean and MockMvcTester
- Offers best practices for AssertJ-style fluent assertions
- Details integration testing strategies using Testcontainers and @ServiceConnection
- Provides guidance on test organization, naming conventions, and coverage goals
- Includes migration and compatibility notes for Spring Boot 3 vs 4
When to use it
- When you need to determine the most efficient test slice for a specific component
- When setting up or refactoring integration tests with Testcontainers
- When you want to adopt modern, readable assertion styles using AssertJ
- When you need to ensure your test suite follows the Test Pyramid principle
- When you are migrating or developing tests across Spring Boot 3 and 4 versions
Advantages
- Promotes fast, focused tests that improve developer feedback loops
- Standardizes testing patterns across the team
- Reduces boilerplate through modern Spring Boot 4 testing APIs
- Improves test readability and maintainability with fluent assertions
- Provides clear guidance on handling complex dependencies and external services
Usage examples
- “How should I test a Spring Boot 4 controller endpoint?”
- The agent will recommend using @WebMvcTest combined with MockMvcTester for efficient, focused testing of the web layer.
- “What is the modern way to mock a bean in Spring Boot 4?”
- The agent will explain the use of @MockitoBean, noting that @MockBean is deprecated in Spring Boot 4.
- “How do I test a repository that requires a database?”
- The agent will suggest using @DataJpaTest along with Testcontainers and @ServiceConnection for a real database integration.
- “My service method is too complex to test, what should I do?”
- The agent will guide you through refactoring the method into smaller, testable units before writing the tests.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/github/spring-boot-testing/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip spring-boot-testing.zip -d .agents/skills
Documentation by kartikdhiman
Spring Boot Testing
This skill provides expert guidance for testing Spring Boot applications with modern patterns and best practices. Examples target Spring Boot 4; see the compatibility note below for Boot 3.
Compatibility: detect first
Read the project's Spring Boot version and test dependencies before writing tests, and do not upgrade them implicitly.
| Spring Boot 3.x | Spring Boot 4.x | |
|---|---|---|
| JUnit | 5 (Jupiter) | 6 by default (same org.junit.jupiter.api annotations; JUnit 5 tests keep working) |
| Mock beans | @MockitoBean / @MockitoSpyBean from 3.4 (Spring Framework 6.2); @MockBean / @SpyBean are deprecated | @MockitoBean replaces @MockBean (do not use the old ones) |
| Test starters | spring-boot-starter-test covers everything | modular: add spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test, ... |
| Slice imports | org.springframework.boot.test.autoconfigure... | moved, e.g. org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest |
| Testcontainers | 1.x names | 2.x names (testcontainers-postgresql) |
Details: references/sb4-migration.md, references/mockitobean.md.
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 |
| Repository + JPA queries | @DataJpaTest | references/datajpatest.md |
| REST client + external APIs | @RestClientTest | references/restclienttest.md |
| JSON (de)serialization | @JsonTest | references/test-slices-overview.md |
| Full application | @SpringBootTest | references/test-slices-overview.md |
Test Slices Reference
references/test-slices-overview.md - Decision matrix and comparison
references/webmvctest.md - Web layer with MockMvc
references/datajpatest.md - Data layer with Testcontainers
references/restclienttest.md - REST client testing
Testing Tools Reference
references/mockmvc-tester.md - AssertJ-style MockMvc (3.2+)
references/mockmvc-classic.md - Traditional MockMvc (pre-3.2)
references/resttestclient.md - Spring Boot 4+ REST client
references/mockitobean.md - Mocking dependencies
Assertion Libraries
references/assertj-basics.md - Scalars, strings, booleans, dates
references/assertj-collections.md - Lists, Sets, Maps, arrays
Testcontainers and integration tests
references/testcontainers-jdbc.md -
@ServiceConnectionquickstart, PostgreSQL, MySQL, etc.references/failsafe-integration-tests.md -
*ITclasses silently skipped unless Failsafe is bound; run./mvnw verify
Maven gotcha: Failsafe declared only in
<pluginManagement>means*ITtests never run. Declare it in<build><plugins>with theintegration-testandverifygoals and run./mvnw verify.
Test Data Generation
references/instancio.md - Generate complex test objects (3+ properties)
Performance & Migration
references/context-caching.md - Speed up test suites
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 configSpring 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)
See also: https://docs.spring.io/spring-boot/reference/testing/spring-boot-applications.html and https://docs.spring.io/spring-boot/reference/features/dev-services.html.
<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>Files
- ATTRIBUTION.mdAdded by AutoGineer879 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md8.3 KiB
- references/assertj-basics.md4.3 KiB
- references/assertj-collections.md4.9 KiB
- references/context-caching.md2.4 KiB
- references/datajpatest.md5.0 KiB
- references/failsafe-integration-tests.md2.5 KiB
- references/instancio.md4.9 KiB
- references/mockitobean.md4.5 KiB
- references/mockmvc-classic.md5.8 KiB
- references/mockmvc-tester.md7.5 KiB
- references/restclienttest.md4.6 KiB
- references/resttestclient.md4.9 KiB
- references/sb4-migration.md3.3 KiB
- references/test-slices-overview.md5.5 KiB
- references/testcontainers-jdbc.md7.7 KiB
- references/webmvctest.md3.6 KiB
references/datajpatest.md
@DataJpaTest
Testing JPA repositories with isolated data layer slice.
Basic Structure
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryTest {
@Container
@ServiceConnection
// Testcontainers 2.x: org.testcontainers.postgresql.PostgreSQLContainer (non-generic); 1.x: PostgreSQLContainer<?> in org.testcontainers.containers
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
@Autowired
private OrderRepository orderRepository;
@Autowired
private TestEntityManager entityManager;
}What Gets Loaded
Repository beans
EntityManager / TestEntityManager
DataSource
Transaction manager
No web layer, no services, no controllers
Testing Custom Queries
@Test
void shouldFindOrdersByStatus() {
// Given - Using var for cleaner code
var pending = new Order("PENDING");
var completed = new Order("COMPLETED");
entityManager.persist(pending);
entityManager.persist(completed);
entityManager.flush();
// When
var pendingOrders = orderRepository.findByStatus("PENDING");
// Then - Using sequenced collection methods
assertThat(pendingOrders).hasSize(1);
assertThat(pendingOrders.getFirst().getStatus()).isEqualTo("PENDING");
}Testing Native Queries
@Test
void shouldExecuteNativeQuery() {
entityManager.persist(new Order("PENDING", BigDecimal.valueOf(100)));
entityManager.persist(new Order("PENDING", BigDecimal.valueOf(200)));
entityManager.flush();
var total = orderRepository.calculatePendingTotal();
assertThat(total).isEqualTo(new BigDecimal("300.00"));
}Testing Pagination
@Test
void shouldReturnPagedResults() {
// Insert 20 orders using IntStream
IntStream.range(0, 20).forEach(i -> {
entityManager.persist(new Order("PENDING"));
});
entityManager.flush();
var page = orderRepository.findByStatus("PENDING", PageRequest.of(0, 10));
assertThat(page.getContent()).hasSize(10);
assertThat(page.getTotalElements()).isEqualTo(20);
assertThat(page.getContent().getFirst().getStatus()).isEqualTo("PENDING");
}Testing Lazy Loading
@Test
void shouldLazyLoadOrderItems() {
var order = new Order("PENDING");
order.addItem(new OrderItem("Product", 2));
entityManager.persist(order);
entityManager.flush();
entityManager.clear(); // Detach from persistence context
var found = orderRepository.findById(order.getId());
assertThat(found).isPresent();
// This will trigger lazy loading
assertThat(found.get().getItems()).hasSize(1);
assertThat(found.get().getItems().getFirst().getProduct()).isEqualTo("Product");
}Testing Cascading
@Test
void shouldCascadeDelete() {
var order = new Order("PENDING");
order.addItem(new OrderItem("Product", 2));
entityManager.persist(order);
entityManager.flush();
orderRepository.delete(order);
entityManager.flush();
assertThat(entityManager.find(OrderItem.class, order.getItems().getFirst().getId()))
.isNull();
}Testing @Query Methods
@Query("SELECT o FROM Order o WHERE o.createdAt > :date AND o.status = :status")
List<Order> findRecentByStatus(@Param("date") LocalDateTime date,
@Param("status") String status);
@Test
void shouldFindRecentOrders() {
var old = new Order("PENDING");
old.setCreatedAt(LocalDateTime.now().minusDays(10));
var recent = new Order("PENDING");
recent.setCreatedAt(LocalDateTime.now().minusHours(1));
entityManager.persist(old);
entityManager.persist(recent);
entityManager.flush();
var recentOrders = orderRepository.findRecentByStatus(
LocalDateTime.now().minusDays(1), "PENDING");
assertThat(recentOrders).hasSize(1);
assertThat(recentOrders.getFirst().getId()).isEqualTo(recent.getId());
}Using H2 vs Real Database
H2 (Default - Not Recommended for Production Parity)
@DataJpaTest // Uses embedded H2 by default
class OrderRepositoryH2Test {
// Fast but may miss DB-specific issues
}Testcontainers (Recommended)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class OrderRepositoryPostgresTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:18");
}Transaction Behavior
Tests are @Transactional by default and roll back after each test.
@Test
@Rollback(false) // Don't roll back (rarely needed)
void shouldPersistData() {
orderRepository.save(new Order("PENDING"));
// Data will remain in database after test
}Key Points
Use TestEntityManager for setup data
Always flush() after persist() to trigger SQL
Clear() the entity manager to test lazy loading
Use real database (Testcontainers) for accurate results
Test both success and failure cases
Leverage Java 25 var keyword for cleaner variable declarations
Use sequenced collection methods (getFirst(), getLast(), reversed())
Requirements and compatibility
Written for: GitHub Copilot
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Security
No issues found by our static scan· No issues found
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- First committed by
kartikdhiman
- Publisher
- GitHub (Official)
- Distributed by
- GitHub
- Source
- github/awesome-copilot · skills/spring-boot-testing · commit 797337f
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
- Contributors
- jdubois, kartikdhiman
AutoGineer is not affiliated with or endorsed by kartikdhiman or GitHub.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download spring-boot-testing.zip