Index of every page on this site: llms.txt
All skills
github avatar

/spring-boot-testing

@f10fdb8 official
by githubgithub/awesome-copilot42k stars
5,426
Run it yourself

Expert Spring Boot testing specialist that selects the best testing techniques for your situation: test slices, Testcontainers with @ServiceConnection, Failsafe integration tests, MockitoBean, JUnit and AssertJ. Written for Spring Boot 4 with notes for Boot 3.

Use this Skill: https://skilld.dev/gh/github/awesome-copilot/spring-boot-testing

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referenceswebmvctest.md

≈913 tokens on demand. Your agent reads this file only when SKILL.md points to it.

@WebMvcTest

Testing Spring MVC controllers with focused slice tests.

Basic Structure

@WebMvcTest(OrderController.class)
class OrderControllerTest {
  
  @Autowired
  private MockMvcTester mvc;
  
  @MockitoBean
  private OrderService orderService;
  
  @MockitoBean
  private UserService userService;
}

What Gets Loaded

  • The specified controller(s)
  • Spring MVC infrastructure (HandlerMapping, HandlerAdapter)
  • Jackson ObjectMapper (for JSON)
  • Exception handlers (@ControllerAdvice)
  • Spring Security filters (if on classpath)
  • Validation (if on classpath)

Testing GET Endpoints

@Test
void shouldReturnOrder() {
  var order = new Order(1L, "PENDING", BigDecimal.valueOf(99.99));
  given(orderService.findById(1L)).willReturn(order);
  
  assertThat(mvc.get().uri("/orders/1"))
    .hasStatusOk()
    .hasContentType(MediaType.APPLICATION_JSON)
    .bodyJson()
    .extractingPath("$.status")
    .isEqualTo("PENDING");
}

Testing POST with Request Body

Using Text Blocks (Java 25)

@Test
void shouldCreateOrder() {
  given(orderService.create(any(OrderRequest.class))).willReturn(1L);
  
  var json = """
    {
      "product": "Product A",
      "quantity": 2
    }
    """;
  
  assertThat(mvc.post().uri("/orders")
    .contentType(MediaType.APPLICATION_JSON)
    .content(json))
    .hasStatus(HttpStatus.CREATED)
    .hasHeader("Location", "/orders/1");
}

Using Records

record OrderRequest(String product, int quantity) {}

@Test
void shouldCreateOrderWithRecord() {
  var request = new OrderRequest("Product A", 2);
  given(orderService.create(any())).willReturn(1L);
  
  assertThat(mvc.post().uri("/orders")
    .contentType(MediaType.APPLICATION_JSON)
    .content(json.write(request).getJson()))
    .hasStatus(HttpStatus.CREATED);
}

Testing Validation Errors

@Test
void shouldRejectInvalidOrder() {
  var invalidJson = """
    {
      "product": "",
      "quantity": -1
    }
    """;
  
  assertThat(mvc.post().uri("/orders")
    .contentType(MediaType.APPLICATION_JSON)
    .content(invalidJson))
    .hasStatus(HttpStatus.BAD_REQUEST)
    .bodyJson()
    .hasPath("$.errors");
}

Testing Query Parameters

@Test
void shouldFilterOrdersByStatus() {
  assertThat(mvc.get().uri("/orders?status=PENDING"))
    .hasStatusOk();
  
  verify(orderService).findByStatus(OrderStatus.PENDING);
}

Testing Path Variables

@Test
void shouldCancelOrder() {
  assertThat(mvc.put().uri("/orders/123/cancel"))
    .hasStatusOk();
  
  verify(orderService).cancel(123L);
}

Testing with Security

@Test
@WithMockUser(roles = "ADMIN")
void adminShouldDeleteOrder() {
  assertThat(mvc.delete().uri("/orders/1"))
    .hasStatus(HttpStatus.NO_CONTENT);
}

@Test
void anonymousUserShouldBeForbidden() {
  assertThat(mvc.delete().uri("/orders/1"))
    .hasStatus(HttpStatus.UNAUTHORIZED);
}

Multiple Controllers

@WebMvcTest({OrderController.class, ProductController.class})
class WebLayerTest {
  // Tests multiple controllers in one slice
}

Excluding Auto-Configuration

@WebMvcTest(OrderController.class)
@AutoConfigureMockMvc(addFilters = false) // Skip security filters
class OrderControllerWithoutSecurityTest {
  // Tests without security filters
}

Key Points

  1. Always mock services with @MockitoBean
  2. Use MockMvcTester for AssertJ-style assertions
  3. Test HTTP semantics (status, headers, content-type)
  4. Verify service method calls when side effects matter
  5. Don't test business logic here - that's for unit tests
  6. Leverage Java 25 text blocks for JSON payloads

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts18d4 checks · Risk SAFE
  • Gen Agent Trust Hub18d

    This skill is a comprehensive educational resource for Spring Boot testing. It provides best practices and code templates for modern Java testing frameworks. No malicious patterns, vulnerabilities, or security risks were identified during the analysis.

  • Socket18d

    No alerts

  • Snyk18d

    Risk: LOW · No issues

  • ZeroLeaks7mo

    Score: 93/100 · 2 sections analyzed

Signed by skilld at f10fdb8. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated last month
  • Testing
  • spring-boot
  • junit
  • assertj
  • mockmvc
  • testcontainers
  • java
  • mockito
  • integration-testing
  • webmvctest

README badge

README badge for github/awesome-copilot/spring-boot-testing

Guides Spring Boot 4 testing with test slices (@WebMvcTest, @DataJpaTest, @RestClientTest), modern assertion libraries (AssertJ, MockMvcTester), and practical patterns like Testcontainers for database integration and context caching for performance. Covers the test pyramid, complexity assessment, and 80% coverage goals.

Generated from the current SKILL.md.

Does this skill work with Spring Boot 3, or is it Spring Boot 4 only?
This skill is written for Spring Boot 4. It covers Spring Boot 4-specific features like RestTestClient, @MockitoBean, and MockMvcTester. Some patterns (like traditional MockMvc) have backward-compatible alternatives documented, but the primary guidance assumes Spring Boot 4.
What assertion library does this skill recommend?
AssertJ. The skill explicitly prefers AssertJ's fluent, readable assertion style over verbose matchers, and includes references for assertions on scalars, collections, and other data types.
Does this cover testing with real databases, or only mocks?
Both. The skill recommends Testcontainers for data layer tests (@DataJpaTest) to use real databases in tests, and includes references for PostgreSQL, MySQL, and other JDBC sources.
What's the recommended test coverage target?
80% as a practical balance between quality and effort. The skill prioritizes business-critical paths, complex algorithms, error handling, and integration points over achieving maximum coverage.
Does this skill help with test data generation?
Yes. It references Instancio for generating complex test objects with 3+ properties, reducing boilerplate in test setup.

Generated from the current SKILL.md. These answers refresh after source changes.