MockMvcによるWebコントローラーのテスト
実際のサーバーを起動せずにHTTPリクエストをシミュレートできるMockMvcを使い、RESTエンドポイントに焦点を絞ったテストを書きます。
「MockMvcによるWebコントローラーのテスト」はCoddyKit上の無料Spring Boot 4 Complete Guideレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Complete Guide学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Test Controllers in Isolation?
Controller tests verify routing, request mapping, status codes, and JSON serialization without the cost of a full server. MockMvc makes this fast and precise.
Introducing @WebMvcTest
The @WebMvcTest annotation loads only the web layer, your controllers and their supporting beans, keeping the test slice small and quick.
@WebMvcTest(UserController.class)
class UserControllerTest {
}Injecting MockMvc
Inside a @WebMvcTest, Spring provides an auto-configured MockMvc instance you autowire to perform simulated requests.
@Autowired
MockMvc mockMvc;Performing a GET Request
Use the fluent API to perform a request and chain expectations on the response.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Mocking the Service Layer
Controllers depend on services, so you replace them with mocks using @MockBean. This isolates the controller from real business logic.
@MockBean
UserService userService;Stubbing Behavior
Combine Mockito stubbing with the request to control what the service returns.
when(userService.find(1L)).thenReturn(new User("Ada"));Asserting JSON Content
Use jsonPath to verify specific fields in the response body.
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Testing POST with a Body
Send a JSON payload and assert the created status, verifying your endpoint accepts and processes input correctly.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());Verifying Validation Errors
Send invalid input and assert a 400 Bad Request to confirm your validation rules actually fire.
mockMvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content("{}"))
.andExpect(status().isBadRequest());Verifying Interactions
Use Mockito's verify to confirm the controller actually called the service the expected number of times.
verify(userService).find(1L);When to Use Full Integration Tests
MockMvc slice tests are fast but mock the service. For end-to-end confidence across the real stack, complement them with full @SpringBootTest integration tests.
Quick Check
Test your understanding of MockMvc controller testing.
Recap
You used @WebMvcTest with MockMvc to test endpoints, mocked services with @MockBean, and asserted status codes and JSON. These slice tests are a fast first line of defense.
AI チューターと学ぶ Java — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 21
- レッスン
- 84
よくある質問
「MockMvcによるWebコントローラーのテスト」レッスンは無料ですか?
はい。「MockMvcによるWebコントローラーのテスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Complete Guideコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Complete Guideコースには全4レッスンが含まれています。
「MockMvcによるWebコントローラーのテスト」で何を学びますか?
実際のサーバーを起動せずにHTTPリクエストをシミュレートできるMockMvcを使い、RESTエンドポイントに焦点を絞ったテストを書きます。 ブラウザで直接実行するハンズオンコードでSpring Boot 4 Complete Guideを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Spring Boot 4 Complete Guideを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのSpring Boot 4 Complete Guideは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「MockMvcによるWebコントローラーのテスト」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このSpring Boot 4 Complete Guideレッスンでコードを書いて実行できますか?
はい。すべてのSpring Boot 4 Complete Guideレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- JUnitとMockitoによる単体テスト
- Spring Bootによる結合テスト
- スライステストとTestcontainers
- MockMvcによるWebコントローラーのテスト