Pengujian Lapisan Web dengan MockMvc
Uji controller dengan @WebMvcTest.
Pengujian Lapisan Web dengan MockMvc adalah pelajaran Spring Boot 4 Microservices & REST APIs gratis di CoddyKit. Ini adalah pelajaran 2 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Spring Boot 4 Microservices & REST APIs, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Spring Boot 4 Microservices & REST APIs mencakup 4 pelajaran total.
Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.
Testing the Web Layer
Web layer tests verify your controllers — request mapping, validation, serialization, and status codes — without starting a full server.
Spring Boot provides @WebMvcTest and MockMvc for this.
@WebMvcTest
@WebMvcTest loads only the web slice: controllers, filters, and converters. Services and repositories are not loaded — you mock them.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired
MockMvc mockMvc;
@MockBean
UserService userService;
}MockMvc.perform
MockMvc simulates HTTP requests against your controller without a network.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Mocking the Service
Use @MockBean to replace the service in the context, then stub it with Mockito.
@Test
void returnsUser() throws Exception {
when(userService.getById("1"))
.thenReturn(new User("1", "Alice"));
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());
}Asserting JSON with jsonPath
jsonPath verifies fields in the JSON response body.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Alice"))
.andExpect(jsonPath("$.id").value("1"));Testing POST Requests
Send a JSON body with content and contentType.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Bob\"}"))
.andExpect(status().isCreated());Asserting Error Statuses
Verify 404 or 400 responses for missing resources or invalid input.
when(userService.getById("99"))
.thenThrow(new NotFoundException());
mockMvc.perform(get("/users/99"))
.andExpect(status().isNotFound());Testing Validation
When a request fails bean validation, expect a 400 Bad Request.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest());Checking Headers
Assert response headers such as Location after a create.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Bob\"}"))
.andExpect(header().string("Location",
"/users/2"));Query Parameters
Add request parameters with param.
mockMvc.perform(get("/users")
.param("name", "Alice"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.length()").value(1));Printing the Result
Use andDo(print()) to log the full request and response while debugging.
mockMvc.perform(get("/users/1"))
.andDo(print())
.andExpect(status().isOk());Quick Check
Test your understanding of MockMvc.
Recap
You learned to test controllers in isolation:
@WebMvcTestloads only the web sliceMockMvc.performsimulates requests@MockBeanreplaces servicesjsonPath,status(),header()for assertions
Pertanyaan yang Sering Diajukan
Apakah pelajaran “Pengujian Lapisan Web dengan MockMvc” gratis?
Ya — teks lengkap “Pengujian Lapisan Web dengan MockMvc” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Spring Boot 4 Microservices & REST APIs, upgrade ke CoddyKit PRO. Kursus Spring Boot 4 Microservices & REST APIs mencakup 4 pelajaran total.
Apa yang akan aku pelajari di “Pengujian Lapisan Web dengan MockMvc”?
Uji controller dengan @WebMvcTest. Kamu berlatih Spring Boot 4 Microservices & REST APIs dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.
Apakah aku perlu pengalaman untuk memulai Spring Boot 4 Microservices & REST APIs?
Tidak diperlukan pengalaman sebelumnya. Spring Boot 4 Microservices & REST APIs di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 2 dari 4.
Berapa lama pelajaran “Pengujian Lapisan Web dengan MockMvc” memakan waktu?
Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.
Bisakah aku menulis dan menjalankan kode dalam pelajaran Spring Boot 4 Microservices & REST APIs ini?
Ya. Setiap pelajaran Spring Boot 4 Microservices & REST APIs menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.
Semua pelajaran dalam kursus ini
- Pengujian Unit dengan JUnit dan Mockito
- Pengujian Lapisan Web dengan MockMvc
- Pengujian Integrasi dengan @SpringBootTest
- Dependensi Nyata dengan Testcontainers