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.
Provides testing patterns for Spring Boot applications spanning unit, slice, integration, and container-based tests using JUnit 5, Mockito, and Testcontainers, with an emphasis on performance-optimized slice testing. It is meant for writing tests for services and repositories, testing REST APIs, and configuring real dependencies through containers. A test-architecture philosophy separates fast isolated unit tests without a Spring context, minimal-context slice tests for individual layers, and full-context integration tests, each with an explicit time budget.
Unit tests use @ExtendWith(MockitoExtension.class) with @Mock and @InjectMocks and target under 50ms. Slice tests use @DataJpaTest for repositories, @WebMvcTest or @WebFluxTest for controllers exercised through MockMvc, and @JsonTest for serialization, targeting under 100ms. Integration tests use @SpringBootTest for the full context and target under 500ms. Testcontainers are wired with @ServiceConnection on Spring Boot 3.5 and later, preferred over @DynamicPropertySource, with @Testcontainers managing lifecycle; a @TestConfiguration bean such as a PostgreSQLContainer is imported into test classes.
The guidance also covers required dependencies (spring-boot-starter-test and testcontainers junit-jupiter), a GitHub Actions CI workflow, and validation checkpoints like confirming containers run and the context loads. Best practices stress choosing the right test type per layer, reusing Testcontainers at the JVM level with withReuse and the TESTCONTAINERS_REUSE_ENABLE flag, initializing deterministic test data in @BeforeEach, mocking external services while using real databases only when necessary, and avoiding @DirtiesContext because it forces a costly context rebuild.
@DataJpaTest for repositories, @WebMvcTest or @WebFluxTest for controllers, @JsonTest for JSON serialization, and @SpringBootTest only for full integration with the complete context.
Prefer @ServiceConnection for cleaner container wiring over @DynamicPropertySource, defining the container as a @Bean in a @TestConfiguration and importing it with @Import.
Under 50ms for unit tests, under 100ms for slice tests, and under 500ms for integration tests.
It forces the Spring context to rebuild, which significantly hurts test performance. It should only be used when absolutely necessary.
At the JVM level by combining withReuse(true) with the TESTCONTAINERS_REUSE_ENABLE environment flag, so the same container is shared rather than recreated.
Quick Setup:
.claude/skills/Repository
giuseppe-trisciuoglio/developer-kit