a-pavithraa/springboot-skills-marketplace / plugins/springboot-architecture/skills/writing-springboot-tests
writing-springboot-tests
VerifiedUse when writing or adding tests or integration tests for Spring Boot code at a service's edges: HTTP clients that call other services (WireMock: 4xx and 5xx responses, timeouts, retries), Kafka or RabbitMQ listeners (redelivery, poison messages, dead-letter topics), events published to other services, or full-API tests against real databases with Testcontainers; domain logic whose rules must hold for every input (calculations, value objects, state transitions, parsing and formatting), tested as properties over generated inputs; also when a Boot 4 test needs the right imports, slices or container wiring. Supplies verified Boot 4.1 templates and the framework traps that make such tests pass without proving anything. Not for reviewing existing tests (see code-reviewer) or Boot 3 to 4 test migration (see springboot-migration).
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 7.9 KB |
| assets/api-integration-test.java | other | 5.1 KB |
| assets/event-publication-test.java | other | 6.2 KB |
| assets/http-client-wiremock-test.java | other | 6.9 KB |
| assets/message-listener-test.java | other | 6.6 KB |
| assets/personas-db.java | other | 1.8 KB |
| assets/personas-jwt.java | other | 2.3 KB |
| assets/personas-oidc.java | other | 2.9 KB |
| assets/pitest-plugin.xml | config | 1.2 KB |
| assets/property-test.java | other | 4.6 KB |
| assets/repository-slice-test.java | other | 2.6 KB |
| assets/route-access-test.java | other | 4.4 KB |
| assets/service-unit-test.java | other | 5.4 KB |
| assets/testcontainers-configuration.java | other | 2.4 KB |
| assets/webmvc-slice-test.java | other | 4.3 KB |
assets/webmvc-slice-test.java
View on GitHubpackage {{PACKAGE}}.orders.web;
import {{PACKAGE}}.orders.domain.InsufficientStockException;
import {{PACKAGE}}.orders.domain.Order;
import {{PACKAGE}}.orders.domain.OrderService;
import {{PACKAGE}}.orders.domain.OrderStatus;
import {{PACKAGE}}.orders.domain.PlaceOrder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.assertj.MockMvcTester;
import java.math.BigDecimal;
import java.time.Instant;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.verifyNoInteractions;
/**
* Web slice: loads only OrderController, the MVC machinery and @RestControllerAdvice handlers.
* It tests what the service test can't see: mapping, validation, status codes, JSON shape, error bodies.
*
* Expected statuses come from the API contract. The creating-springboot-projects GlobalExceptionHandler
* answers invalid input with 400 and a ProblemDetail listing the errors, and broken business rules
* (DomainException) with 422: assert what YOUR handler documents, and if the code disagrees with the
* contract, report it rather than changing the test.
*/
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired
MockMvcTester mvc;
@MockitoBean
OrderService orders; // the layer below the controller: mocked, because its rules have their own test
@Test
void placingAnOrderAnswersCreatedWithTheOrderAndItsLocation() {
given(orders.place(any(PlaceOrder.class))).willReturn(new Order(
"O-1", "P-1", 3, new BigDecimal("37.50"), OrderStatus.PLACED, Instant.parse("2026-10-21T10:00:00Z")));
var result = mvc.post().uri("/api/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"productCode": "P-1", "quantity": 3}
""");
assertThat(result)
.hasStatus(HttpStatus.CREATED)
.hasHeader("Location", "http://localhost/api/orders/O-1");
assertThat(result).bodyJson().isLenientlyEqualTo("""
{"id": "O-1", "productCode": "P-1", "quantity": 3, "total": 37.50, "status": "PLACED"}
""");
}
@Test
void rejectsAMissingProductCodeWithoutCallingTheService() {
var result = mvc.post().uri("/api/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"quantity": 3}
""");
assertThat(result).hasStatus(HttpStatus.BAD_REQUEST);
assertThat(result).bodyJson().extractingPath("$.errors").asArray().isNotEmpty();
verifyNoInteractions(orders); // invalid input must never reach the business layer
}
@Test
void answersInsufficientStockAsAProblemDetail() {
given(orders.place(any(PlaceOrder.class))).willThrow(new InsufficientStockException("P-1", 3, 1));
var result = mvc.post().uri("/api/orders")
.contentType(MediaType.APPLICATION_JSON)
.content("""
{"productCode": "P-1", "quantity": 3}
""");
assertThat(result).hasStatus(HttpStatus.UNPROCESSABLE_ENTITY);
assertThat(result).bodyJson().extractingPath("$.detail").asString().contains("P-1");
}
@Test
void answersNotFoundForAnUnknownOrder() {
given(orders.find("O-404")).willReturn(java.util.Optional.empty());
assertThat(mvc.get().uri("/api/orders/O-404"))
.hasStatus(HttpStatus.NOT_FOUND);
}
}
// With Spring Security on the classpath, also test who may call it:
// mvc.post().uri(...).with(user("ann").roles("CUSTOMER")).with(csrf()) → allowed
// the same request without .with(user(...)) → 401
// (static imports from org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors)
// user(...).roles(...) skips the app's own role mapping; personas-*.java sign in through it.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |