0Pricing
Spring Boot 4 Microservices & REST APIs · レッスン

MockMvcによるWeb層テスト

@WebMvcTestでコントローラーをテストします

「MockMvcによるWeb層テスト」はCoddyKit上の無料Spring Boot 4 Microservices & REST APIsレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはSpring Boot 4 Microservices & REST APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

このレッスンの一部はまだ翻訳されておらず、英語で表示されています。

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:

  • @WebMvcTest loads only the web slice
  • MockMvc.perform simulates requests
  • @MockBean replaces services
  • jsonPath, status(), header() for assertions

よくある質問

「MockMvcによるWeb層テスト」レッスンは無料ですか?

はい。「MockMvcによるWeb層テスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Spring Boot 4 Microservices & REST APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Spring Boot 4 Microservices & REST APIsコースには全4レッスンが含まれています。

「MockMvcによるWeb層テスト」で何を学びますか?

@WebMvcTestでコントローラーをテストします ブラウザで直接実行するハンズオンコードでSpring Boot 4 Microservices & REST APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

Spring Boot 4 Microservices & REST APIsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのSpring Boot 4 Microservices & REST APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。

「MockMvcによるWeb層テスト」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このSpring Boot 4 Microservices & REST APIsレッスンでコードを書いて実行できますか?

はい。すべてのSpring Boot 4 Microservices & REST APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. JUnitとMockitoによる単体テスト
  2. MockMvcによるWeb層テスト
  3. @SpringBootTestによる統合テスト
  4. Testcontainersによる実際の依存関係のテスト
← Spring Boot 4 Microservices & REST APIsに戻る