Testowanie API RESTful
Używaj `MockMvc` lub `WebTestClient` do tworzenia kompleksowych testów integracyjnych kontrolerów REST aplikacji Spring Boot.
Testowanie API RESTful to bezpłatna lekcja Testing Mastery: JUnit, Mockito & Integration Tests na CoddyKit. To lekcja 2 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Testing Mastery: JUnit, Mockito & Integration Tests, a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Testing Mastery: JUnit, Mockito & Integration Tests zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
Why Test REST APIs?
RESTful APIs are the backbone of many modern applications. Testing them is crucial to ensure they work as expected, handle various inputs, and return correct responses.
This lesson focuses on how to write integration tests for your Spring Boot REST controllers using powerful tools: MockMvc and WebTestClient.
Spring Boot Test Setup
To test Spring Boot controllers, we need a special setup. The @SpringBootTest annotation loads the full application context, and @AutoConfigureMockMvc configures MockMvc for us.
Here's a basic structure for a controller test class:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class MyApiControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void contextLoads() {
// Your tests will go here
}
}Introducing MockMvc
MockMvc allows you to test your Spring MVC controllers without starting a full HTTP server. It simulates HTTP requests and responses, making tests fast and isolated.
It's ideal for testing the controller layer, ensuring routes, request mappings, and response formats are correct.
MockMvc: Testing GET Requests
Let's test a simple GET endpoint, for example, /api/hello which returns "Hello, CoddyKit!". We'll verify the HTTP status code and the response content.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Assume a @RestController with @GetMapping("/api/hello") returning "Hello, CoddyKit!"
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testHelloEndpoint() throws Exception {
mockMvc.perform(get("/api/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, CoddyKit!"));
}
}MockMvc: GET with Path Variables
APIs often use path variables to identify resources, like /api/users/{id}. MockMvc handles these naturally.
Here's how to test an endpoint that takes an ID:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Assume @GetMapping("/api/users/{id}") returns "User: " + id
@SpringBootTest
@AutoConfigureMockMvc
public class UserControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testGetUserById() throws Exception {
mockMvc.perform(get("/api/users/{id}", 123))
.andExpect(status().isOk())
.andExpect(content().string("User: 123"));
}
}MockMvc: Testing POST Requests
For POST requests, you typically send a request body, often in JSON format. We can specify the content type and body using MockMvc.
Let's test an endpoint that creates an item:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
// Assume @PostMapping("/api/items") creates an item and returns it
@SpringBootTest
@AutoConfigureMockMvc
public class ItemControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void testCreateItem() throws Exception {
String newItemJson = "{\"name\":\"Laptop\", \"price\":1200}";
mockMvc.perform(post("/api/items")
.contentType(MediaType.APPLICATION_JSON)
.content(newItemJson))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.name").value("Laptop"));
}
}Introducing WebTestClient
WebTestClient is a non-blocking, reactive client for testing web applications. It's part of Spring WebFlux but can also be used to test Spring MVC controllers.
- It can perform actual HTTP calls (if configured to hit a running server).
- It can also be backed by
MockMvcfor server-side testing similar toMockMvcitself, but with a reactive API.
WebTestClient in Action
Using WebTestClient is similar to MockMvc, but its fluent API often feels more modern, especially for reactive applications. Let's re-test our /api/hello endpoint.
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.context.ApplicationContext;
import org.springframework.test.web.reactive.server.WebTestClient;
// For WebTestClient with Spring MVC, we can use @SpringBootTest
// and inject WebTestClient.Builder to build it with MockMvc.webAppContextSetup
// For simplicity, this example assumes a WebFlux app or WebTestClient set up for MockMvc
// @SpringBootTest
// class HelloWebClientTest {
// @Autowired WebApplicationContext wac;
// WebTestClient client;
// @BeforeEach void setup() { client = WebTestClient.bindToApplicationContext(wac).build(); }
// ...
// For a simpler runnable example focusing on WebTestClient usage:
@WebFluxTest // This annotation sets up a minimal reactive context for WebTestClient
public class HelloWebClientTest {
@Autowired
private WebTestClient webTestClient;
@Test
void testHelloEndpoint() {
webTestClient.get().uri("/api/hello")
.exchange()
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello, CoddyKit!");
}
}MockMvc vs. WebTestClient
When should you use MockMvc versus WebTestClient?
MockMvc: Best for traditional Spring MVC applications. It's server-side, simulates requests, and doesn't require a running server, making it fast.WebTestClient: Ideal for reactive Spring WebFlux applications. It also provides a reactive client API for testing Spring MVC apps, offering a more modern, fluent way to write tests, and can even hit a live server for true end-to-end integration tests.
For most Spring Boot REST API integration tests focusing on the controller layer, MockMvc is a solid choice due to its speed and direct integration.
Quick Check: API Testing Tools
You are building a Spring Boot application using traditional Spring MVC. You want to write fast, isolated integration tests for your REST controllers without starting a full HTTP server.
Recap & Next Steps
In this lesson, you learned how to write comprehensive integration tests for your Spring Boot REST controllers. We covered:
- Setting up your test environment with
@SpringBootTestand@AutoConfigureMockMvc. - Using
MockMvcto simulate GET and POST requests, verifying status and content. - Introducing
WebTestClientfor reactive testing and its alternative use cases. - Understanding the differences and when to choose between
MockMvcandWebTestClient.
These tools are essential for building robust and reliable RESTful APIs!
Często zadawane pytania
Czy lekcja „Testowanie API RESTful” jest bezpłatna?
Tak — pełny tekst „Testowanie API RESTful” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Testing Mastery: JUnit, Mockito & Integration Tests, przejdź na CoddyKit PRO. Kurs Testing Mastery: JUnit, Mockito & Integration Tests zawiera 4 lekcji w sumie.
Co nauczysz się w „Testowanie API RESTful”?
Używaj `MockMvc` lub `WebTestClient` do tworzenia kompleksowych testów integracyjnych kontrolerów REST aplikacji Spring Boot. Ćwiczysz Testing Mastery: JUnit, Mockito & Integration Tests z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Testing Mastery: JUnit, Mockito & Integration Tests?
Nie wymagamy żadnego doświadczenia. Testing Mastery: JUnit, Mockito & Integration Tests w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 2 z 4.
Ile czasu zajmuje lekcja „Testowanie API RESTful”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Testing Mastery: JUnit, Mockito & Integration Tests?
Tak. Każda lekcja Testing Mastery: JUnit, Mockito & Integration Tests zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Framework kontekstu testowego Spring
- Testowanie API RESTful
- Wbudowane bazy danych na potrzeby testów
- Testowanie warstwy webowej za pomocą @WebMvcTest i MockMvc