/spring-boot-template:testing-patternsfrom Spring Boot Template
Provides testing patterns for Spring Boot applications using JUnit 5, Mockito, MockMvc, and Testcontainers. Covers unit, slice, and integration tests with positive and negative test cases.
Ships in Spring Boot Template. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Testing strategies for Spring Boot applications. Always write both positive and negative test cases.
| Level | Annotation | Speed | Scope | When to Use |
|---|---|---|---|---|
| Unit | @ExtendWith(MockitoExtension.class) | Fast | Single class | Business logic in services |
| Slice | @WebMvcTest, @DataJpaTest | Medium | One layer | Controllers, repositories |
| Integration | @SpringBootTest | Slow | Full app | End-to-end flows, cross-layer |
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository orderRepository;
@Mock
private ProductService productService;
@InjectMocks
private OrderService orderService;
// ✅ Positive test
@Test
@DisplayName("Should create order with valid items")
void shouldCreateOrder() {
// Given
var request = new OrderRequest(List.of(
new OrderItem(1L, 2)
));
var product = new Product();
product.setId(1L);
product.setPrice(new BigDecimal("10.00"));
when(productService.findById(1L)).thenReturn(product);
when(orderRepository.save(any(Order.class))).thenAnswer(inv -> {
Order o = inv.getArgument(0);
o.setId(1L);
return o;
});
// When
Order result = orderService.create(request);
// Then
assertThat(result.getId()).isEqualTo(1L);
verify(orderRepository).save(any(Order.class));
}
// ✅ Negative test
@Test
@DisplayName("Should throw when product not found")
void shouldThrowWhenProductNotFound() {
// Given
var request = new OrderRequest(List.of(
new OrderItem(999L, 1)
));
when(productService.findById(999L))
.thenThrow(new EntityNotFoundException("Product not found"));
// When & Then
assertThatThrownBy(() -> orderService.create(request))
.isInstanceOf(EntityNotFoundException.class)
.hasMessageContaining("Product not found");
verify(orderRepository, never()).save(any());
}
// ✅ Negative test - empty input
@Test
@DisplayName("Should throw when order has no items")
void shouldThrowWhenNoItems() {
var request = new OrderRequest(List.of());
assertThatThrownBy(() -> orderService.create(request))
.isInstanceOf(IllegalArgumentException.class);
}
}
Spring Boot 4 imports: @WebMvcTest is in org.springframework.boot.webmvc.test.autoconfigure, @DataJpaTest in org.springframework.boot.data.jpa.test.autoconfigure, @MockitoBean in org.springframework.test.context.bean.override.mockito, PostgreSQLContainer in org.testcontainers.postgresql (Testcontainers 2, not generic), JsonMapper in tools.jackson.databind.json (Jackson 3). Full list and test dependencies: spring-boot → references/testing.md.
@WebMvcTest(ProductController.class)
class ProductControllerTest {
@Autowired
private MockMvc mockMvc;
@MockitoBean
private ProductService productService;
@Autowired
private JsonMapper jsonMapper;
// ✅ Positive - successful creation
@Test
@DisplayName("POST /api/v1/products - returns 201")
void createProduct_validRequest_returns201() throws Exception {
var request = new ProductRequest("Widget", new BigDecimal("10.00"));
var product = new Product();
product.setId(1L);
product.setName("Widget");
when(productService.create(any())).thenReturn(product);
mockMvc.perform(post("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonMapper.writeValueAsString(request)))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name").value("Widget"));
}
// ✅ Negative - validation failure
@Test
@DisplayName("POST /api/v1/products - blank name returns 400")
void createProduct_blankName_returns400() throws Exception {
var request = new ProductRequest("", new BigDecimal("10.00"));
mockMvc.perform(post("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.content(jsonMapper.writeValueAsString(request)))
.andExpect(status().isBadRequest())
.andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON))
.andExpect(jsonPath("$.errors[0].field").value("name"))
.andExpect(jsonPath("$.errors[0].code").value("required"));
verify(productService, never()).create(any());
}
// ✅ Negative - not found
@Test
@DisplayName("GET /api/v1/products/999 - returns 404")
void getProduct_notFound_returns404() throws Exception {
when(productService.findById(999L))
.thenThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Product 999 not found"));
mockMvc.perform(get("/api/v1/products/999"))
.andExpect(status().isNotFound())
.andExpect(jsonPath("$.status").value(404));
}
// ✅ Negative - stale version
@Test
@DisplayName("PUT /api/v1/products/1 - stale version returns 409 without errors")
void updateProduct_staleVersion_returns409() throws Exception {
when(productService.update(eq(1L), any()))
.thenThrow(new ObjectOptimisticLockingFailureException(Product.class, 1L));
mockMvc.perform(put("/api/v1/products/1")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"name":"Widget","price":10.0,"version":0}
"""))
.andExpect(status().isConflict())
.andExpect(jsonPath("$.errors").doesNotExist());
}
}
$.status, $.errors[*].field, $.errors[*].code), never on message texts.@WebMvcTest creates no repositories or services: every bean the controller injects needs a @MockitoBean, including a repository newly added to an existing controller.@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
class ProductRepositoryTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:16-alpine");
@Autowired
private ProductRepository productRepository;
@Autowired
private TestEntityManager entityManager;
@Test
@DisplayName("Should find products by name containing")
void shouldFindByNameContaining() {
// Given
var product = new Product();
product.setName("Spring Widget");
product.setPrice(new BigDecimal("10.00"));
entityManager.persistAndFlush(product);
// When
List<Product> results = productRepository
.findByNameContainingIgnoreCase("widget");
// Then
assertThat(results).hasSize(1);
assertThat(results.get(0).getName()).isEqualTo("Spring Widget");
}
@Test
@DisplayName("Should return empty list when no match")
void shouldReturnEmptyWhenNoMatch() {
List<Product> results = productRepository
.findByNameContainingIgnoreCase("nonexistent");
assertThat(results).isEmpty();
}
}
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureRestTestClient
@Testcontainers(disabledWithoutDocker = true)
@ActiveProfiles("test")
class ProductIntegrationTest {
@Container
@ServiceConnection
static PostgreSQLContainer postgres = new PostgreSQLContainer("postgres:16-alpine");
@Autowired
private RestTestClient restTestClient;
@Autowired
private ProductRepository productRepository;
@Autowired
private Flyway flyway;
@Autowired
private JdbcTemplate jdbc;
@Autowired
private BuildProperties buildProperties;
@Test
@DisplayName("Should apply all Flyway migrations")
void migrationsApplied() {
assertThat(flyway.info().current()).isNotNull();
assertThat(flyway.info().pending()).isEmpty();
}
@Test
@DisplayName("Should reject row violating DB constraint")
void databaseRejectsNegativePrice() {
// Migration defines CONSTRAINT ck_products_price CHECK (price >= 0)
assertThatThrownBy(() -> jdbc.update(
"INSERT INTO products (name, price, version) VALUES ('Widget', -1, 0)"))
.isInstanceOf(DataIntegrityViolationException.class);
}
@BeforeEach
void setUp() {
productRepository.deleteAll();
}
@Test
@DisplayName("Full CRUD flow works end-to-end")
void crudFlow() {
// Create
var request = new ProductRequest("Widget", new BigDecimal("10.00"));
var created = restTestClient.post()
.uri("/api/v1/products")
.contentType(MediaType.APPLICATION_JSON)
.body(request)
.exchange()
.expectStatus().isCreated()
.expectBody(ProductResponse.class)
.returnResult()
.getResponseBody();
Long id = created.id();
// Read
restTestClient.get()
.uri("/api/v1/products/{id}", id)
.exchange()
.expectStatus().isOk()
.expectBody(ProductResponse.class)
.value(product -> assertThat(product.name()).isEqualTo("Widget"));
// Delete
restTestClient.delete()
.uri("/api/v1/products/{id}", id)
.exchange()
.expectStatus().isNoContent();
restTestClient.get()
.uri("/api/v1/products/{id}", id)
.exchange()
.expectStatus().isNotFound();
}
// Only when the API is built for a UI (public /actuator/info, see conventions)
@Test
@DisplayName("Health and info are public; other Actuator endpoints are not")
void statusEndpointsArePublic() {
restTestClient.get().uri("/actuator/health").exchange()
.expectStatus().isOk()
.expectBody().jsonPath("$.components.db.status").isEqualTo("UP");
restTestClient.get().uri("/actuator/info").exchange()
.expectStatus().isOk()
.expectBody().jsonPath("$.build.version").isEqualTo(buildProperties.getVersion());
restTestClient.get().uri("/actuator/env").exchange()
.expectStatus().isUnauthorized();
}
}
What the integration tests cover besides CRUD (the last two only when the API is built for a UI, see conventions):
@ManyToOne the API lets a client change, against the real database. A → B is the case that fails with LazyInitializationException when the write is not @Transactional; a mocked @WebMvcTest cannot see it.version; the second returns 409.contract/openapi.json (spring-boot skill, references/ui-contract.md).health and info answer without a token, everything else under /actuator does not.Run them with ./mvnw clean verify. With @Testcontainers(disabledWithoutDocker = true) they are skipped silently when Docker is not available, so check the test report shows them as run, not skipped. With Podman instead of Docker:
# macOS (podman machine); on Linux: unix:///run/user/$(id -u)/podman/podman.sock
export DOCKER_HOST=unix://$(podman machine inspect --format '{{.ConnectionInfo.PodmanSocket.Path}}')
export TESTCONTAINERS_RYUK_DISABLED=true
./mvnw clean verify
@TestConfiguration(proxyBeanMethods = false)
public class TestcontainersConfig {
@Bean
@ServiceConnection
public PostgreSQLContainer postgresContainer() {
return new PostgreSQLContainer("postgres:16-alpine");
}
}
// Use with @Import
@SpringBootTest
@Import(TestcontainersConfig.class)
class AnyIntegrationTest {
// ...
}
@ParameterizedTest
@ValueSource(strings = {"", " ", "ab"})
@DisplayName("Should reject invalid usernames")
void shouldRejectInvalidUsername(String username) {
var request = new UserRequest(username, "[email protected]");
assertThatThrownBy(() -> userService.create(request))
.isInstanceOf(ConstraintViolationException.class);
}
@ParameterizedTest
@CsvSource({
"[email protected], ADMIN, true",
"[email protected], USER, true",
"[email protected], GUEST, false"
})
@DisplayName("Should check access by role")
void shouldCheckAccessByRole(String email, String role, boolean expected) {
assertThat(securityService.hasAccess(email, role)).isEqualTo(expected);
}
| Pattern | Use For |
|---|---|
@ExtendWith(MockitoExtension.class) | Unit tests with mocks |
@WebMvcTest(Controller.class) | Controller tests with MockMvc |
@DataJpaTest | Repository tests with real DB |
@SpringBootTest + RANDOM_PORT | Full integration tests |
@ServiceConnection | Auto-configure Testcontainers |
@ParameterizedTest | Multiple inputs, same assertion |
assertThatThrownBy() | Negative test - expect exception |
verify(mock, never()) | Verify method was NOT called |
methodUnderTest_condition_expectedResult
Examples: createUser_validRequest_returns201, createUser_duplicateEmail_throws409
What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
npx claudepluginhub piomin/claude-ai-spring-boot --plugin spring-boot-template10 skills in this plugin
/code-qualityReview checklist for Java / Spring Boot code - correctness, security, performance, Spring signals, REST semantics, and code smells; project rules are referenced from conventions, not repeated. Use when user says "review code", "check this PR", "refactor", "check API", or before merging changes./conventionsSpring Boot project conventions and mandatory rules. Auto-loads when working with Spring Boot, Java, or Maven projects, and before a new Spring Boot project or REST API is generated - it asks for the architecture style (layered CRUD, CQRS, Event Sourcing) first. Enforces No-Lombok, constructor injection, RestClient, Flyway for relational databases, Problem Details errors, and other standards; adds OpenAPI contract rules when the API is built for a UI./design-patternsDesign patterns with Java examples - classic (Factory, Builder, Strategy, Observer, Decorator, Adapter) and enterprise/microservices (Saga, Outbox, CQRS). Use when user asks about patterns, designing extensible components, or distributed transaction strategies./event-drivenCQRS and Event Sourcing for Spring Boot 4.x - command and query handlers, read models updated from domain events, transactional outbox with Apache Kafka or in-process events with Spring Modulith, an append-only PostgreSQL event store with aggregates rebuilt from events, upcasting and rebuildable projections, or Axon Framework, as separate command and query services or a single service. Use when the architecture block in the project's CLAUDE.md or AGENTS.md names the cqrs or cqrs-event-sourcing style, or when the user asks for CQRS, Event Sourcing, an event store, an outbox, projections or read models./java-modernJava 21+ features for Spring Boot - records, sealed classes, pattern matching, virtual threads, text blocks. Use when user asks about modern Java, Java 21 features, or when modernizing existing code./jpa-patternsJPA/Hibernate patterns and common pitfalls (N+1, lazy loading, transactions, queries). Use when user has JPA performance issues, LazyInitializationException, or asks about entity relationships and fetching strategies.Other plugins' skills for the same job