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.

referencesrestclienttest.md

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

@RestClientTest

Testing REST clients in isolation with MockRestServiceServer.

Overview

@RestClientTest auto-configures:

  • RestTemplate/RestClient with mock server support
  • Jackson ObjectMapper
  • MockRestServiceServer

Basic Setup

@RestClientTest(WeatherService.class)
class WeatherServiceTest {
  
  @Autowired
  private WeatherService weatherService;
  
  @Autowired
  private MockRestServiceServer server;
}

Testing RestTemplate

@RestClientTest(WeatherService.class)
class WeatherServiceTest {
  
  @Autowired
  private WeatherService weatherService;
  
  @Autowired
  private MockRestServiceServer server;
  
  @Test
  void shouldFetchWeather() {
    // Given
    server.expect(requestTo("https://api.weather.com/v1/current"))
      .andExpect(method(HttpMethod.GET))
      .andExpect(queryParam("city", "Berlin"))
      .andRespond(withSuccess()
        .contentType(MediaType.APPLICATION_JSON)
        .body("{\"temperature\": 22, \"condition\": \"Sunny\"}"));
    
    // When
    Weather weather = weatherService.getCurrentWeather("Berlin");
    
    // Then
    assertThat(weather.getTemperature()).isEqualTo(22);
    assertThat(weather.getCondition()).isEqualTo("Sunny");
  }
}

Testing RestClient (Spring 6.1+)

@RestClientTest(WeatherService.class)
class WeatherServiceTest {
  
  @Autowired
  private WeatherService weatherService;
  
  @Autowired
  private MockRestServiceServer server;
  
  @Test
  void shouldFetchWeatherWithRestClient() {
    server.expect(requestTo("https://api.weather.com/v1/current"))
      .andRespond(withSuccess()
        .body("{\"temperature\": 22}"));
    
    Weather weather = weatherService.getCurrentWeather("Berlin");
    
    assertThat(weather.getTemperature()).isEqualTo(22);
  }
}

Request Matching

Exact URL

server.expect(requestTo("https://api.example.com/users/1"))
  .andRespond(withSuccess());

URL Pattern

server.expect(requestTo(matchesPattern("https://api.example.com/users/\\d+")))
  .andRespond(withSuccess());

HTTP Method

server.expect(ExpectedCount.once(), 
  requestTo("https://api.example.com/users"))
  .andExpect(method(HttpMethod.POST))
  .andRespond(withCreatedEntity(URI.create("/users/1")));

Request Body

server.expect(requestTo("https://api.example.com/users"))
  .andExpect(content().contentType(MediaType.APPLICATION_JSON))
  .andExpect(content().json("{\"name\": \"John\"}"))
  .andRespond(withSuccess());

Headers

server.expect(requestTo("https://api.example.com/users"))
  .andExpect(header("Authorization", "Bearer token123"))
  .andExpect(header("X-Api-Key", "secret"))
  .andRespond(withSuccess());

Response Types

Success with Body

server.expect(requestTo("/users/1"))
  .andRespond(withSuccess()
    .contentType(MediaType.APPLICATION_JSON)
    .body("{\"id\": 1, \"name\": \"John\"}"));

Success from Resource

server.expect(requestTo("/users/1"))
  .andRespond(withSuccess()
    .body(new ClassPathResource("user-response.json")));

Created

server.expect(requestTo("/users"))
  .andExpect(method(HttpMethod.POST))
  .andRespond(withCreatedEntity(URI.create("/users/1")));

Error Response

server.expect(requestTo("/users/999"))
  .andRespond(withResourceNotFound());

server.expect(requestTo("/users"))
  .andRespond(withServerError()
    .body("Internal Server Error"));

server.expect(requestTo("/users"))
  .andRespond(withStatus(HttpStatus.BAD_REQUEST)
    .body("{\"error\": \"Invalid input\"}"));

Verifying Requests

@Test
void shouldCallApi() {
  server.expect(ExpectedCount.once(), 
    requestTo("https://api.example.com/data"))
    .andRespond(withSuccess());
  
  service.fetchData();
  
  server.verify(); // Verify all expectations met
}

Ignoring Extra Requests

@Test
void shouldHandleMultipleCalls() {
  server.expect(ExpectedCount.manyTimes(),
    requestTo(matchesPattern("/api/.*")))
    .andRespond(withSuccess());
  
  // Multiple calls allowed
  service.callApi();
  service.callApi();
  service.callApi();
}

Reset Between Tests

@BeforeEach
void setUp() {
  server.reset();
}

Testing Timeouts

server.expect(requestTo("/slow-endpoint"))
  .andRespond(withSuccess()
    .body("{\"data\": \"test\"}")
    .delay(100, TimeUnit.MILLISECONDS));

// Test timeout handling

Best Practices

  1. Always verify server.verify() at end of test
  2. Use resource files for large JSON responses
  3. Match on minimal set of request attributes
  4. Reset server in @BeforeEach
  5. Test error responses, not just success
  6. Verify request body for POST/PUT calls

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.