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.

referencesmockmvc-classic.md

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

MockMvc Classic

Traditional MockMvc API for Spring MVC controller tests (pre-Spring Boot 3.2 or legacy codebases).

When to Use This Reference

  • The project uses Spring Boot < 3.2 (no MockMvcTester available)
  • Existing tests use mvc.perform(...) and you are maintaining or extending them
  • You need to migrate classic MockMvc tests to MockMvcTester (see migration section below)
  • The user explicitly asks about ResultActions, andExpect(), or Hamcrest-style web assertions

For new tests on Spring Boot 3.2+, prefer mockmvc-tester.md instead.

Setup

@WebMvcTest(OrderController.class)
class OrderControllerTest {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private OrderService orderService;
}

Basic GET Request

@Test
void shouldReturnOrder() throws Exception {
  given(orderService.findById(1L)).willReturn(new Order(1L, "PENDING", 99.99));

  mvc.perform(get("/orders/1"))
    .andExpect(status().isOk())
    .andExpect(content().contentType(MediaType.APPLICATION_JSON))
    .andExpect(jsonPath("$.id").value(1))
    .andExpect(jsonPath("$.status").value("PENDING"))
    .andExpect(jsonPath("$.totalToPay").value(99.99));
}

POST with Request Body

@Test
void shouldCreateOrder() throws Exception {
  given(orderService.create(any(OrderRequest.class))).willReturn(1L);

  mvc.perform(post("/orders")
      .contentType(MediaType.APPLICATION_JSON)
      .content("{\"product\": \"Laptop\", \"quantity\": 2}"))
    .andExpect(status().isCreated())
    .andExpect(header().string("Location", "/orders/1"));
}

PUT Request

@Test
void shouldUpdateOrder() throws Exception {
  mvc.perform(put("/orders/1")
      .contentType(MediaType.APPLICATION_JSON)
      .content("{\"status\": \"COMPLETED\"}"))
    .andExpect(status().isOk());
}

DELETE Request

@Test
void shouldDeleteOrder() throws Exception {
  mvc.perform(delete("/orders/1"))
    .andExpect(status().isNoContent());
}

Status Matchers

.andExpect(status().isOk())           // 200
.andExpect(status().isCreated())      // 201
.andExpect(status().isNoContent())    // 204
.andExpect(status().isBadRequest())   // 400
.andExpect(status().isUnauthorized()) // 401
.andExpect(status().isForbidden())    // 403
.andExpect(status().isNotFound())     // 404
.andExpect(status().is(422))          // arbitrary code

JSON Path Assertions

// Exact value
.andExpect(jsonPath("$.status").value("PENDING"))

// Existence
.andExpect(jsonPath("$.id").exists())
.andExpect(jsonPath("$.deletedAt").doesNotExist())

// Array size
.andExpect(jsonPath("$.items").isArray())
.andExpect(jsonPath("$.items", hasSize(3)))

// Nested field
.andExpect(jsonPath("$.customer.name").value("John Doe"))
.andExpect(jsonPath("$.customer.address.city").value("Berlin"))

// With Hamcrest matchers
.andExpect(jsonPath("$.total", greaterThan(0.0)))
.andExpect(jsonPath("$.description", containsString("order")))

Content Assertions

.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andExpect(content().string(containsString("PENDING")))
.andExpect(content().json("{\"status\":\"PENDING\"}"))

Header Assertions

.andExpect(header().string("Location", "/orders/1"))
.andExpect(header().string("Content-Type", containsString("application/json")))
.andExpect(header().exists("X-Request-Id"))
.andExpect(header().doesNotExist("X-Deprecated"))

Request Parameters and Headers

// Query parameters
mvc.perform(get("/orders").param("status", "PENDING").param("page", "0"))
  .andExpect(status().isOk());

// Path variables
mvc.perform(get("/orders/{id}", 1L))
  .andExpect(status().isOk());

// Request headers
mvc.perform(get("/orders/1").header("X-Api-Key", "secret"))
  .andExpect(status().isOk());

Capturing the Response

@Test
void shouldReturnCreatedId() throws Exception {
  given(orderService.create(any())).willReturn(42L);

  MvcResult result = mvc.perform(post("/orders")
      .contentType(MediaType.APPLICATION_JSON)
      .content("{\"product\": \"Laptop\", \"quantity\": 1}"))
    .andExpect(status().isCreated())
    .andReturn();

  String location = result.getResponse().getHeader("Location");
  assertThat(location).isEqualTo("/orders/42");
}

Chaining with andDo

mvc.perform(get("/orders/1"))
  .andDo(print())              // prints request/response to console (debug)
  .andExpect(status().isOk());

Static Imports

import org.springframework.boot.test.mock.mockito.MockBean;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;
import static org.hamcrest.Matchers.*;

Migration to MockMvcTester

Classic MockMvc MockMvcTester (recommended)
@Autowired MockMvc mvc @Autowired MockMvcTester mvc
mvc.perform(get("/orders/1")) mvc.get().uri("/orders/1")
.andExpect(status().isOk()) .hasStatusOk()
.andExpect(jsonPath("$.status").value("X")) .bodyJson().convertTo(T.class) + AssertJ
throws Exception on every method No checked exception
Hamcrest matchers AssertJ fluent assertions

See mockmvc-tester.md for the full modern API.

Key Points

  1. Every test method must declare throws Exception — perform() throws checked exceptions
  2. Use andDo(print()) during debugging — remove before committing
  3. Prefer jsonPath() over content().string() — more precise field-level assertions
  4. Static imports are required — IDE can auto-add them
  5. Migrate to MockMvcTester when upgrading to Spring Boot 3.2+ for better readability

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.