@WebMvcTestとMockMvcによるWeb層のテスト
@WebMvcTestとMockMvcを使い、完全なアプリケーションコンテキストを起動せずにSpring Bootのコントローラーを単独でスライステストします。
「@WebMvcTestとMockMvcによるWeb層のテスト」はCoddyKit上の無料Testing Mastery: JUnit, Mockito & Integration Testsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはTesting Mastery: JUnit, Mockito & Integration Tests学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Testing Mastery: JUnit, Mockito & Integration Testsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Slice Tests?
Loading the entire Spring context for every controller test is slow. Spring Boot offers test slices that load only the beans you need. @WebMvcTest loads just the web layer.
What @WebMvcTest Loads
@WebMvcTest configures controllers, filters, and JSON converters, but not services or repositories. Those collaborators are supplied as mocks.
Declaring the Test
Target a single controller so the slice stays small and fast.
@WebMvcTest(UserController.class)
class UserControllerTest {
@Autowired MockMvc mockMvc;
}Mocking the Service
The controller's service dependency is replaced with a Mockito mock using @MockBean, which places the mock in the context.
@MockBean
UserService userService;Performing a Request
MockMvc simulates HTTP requests against your controller without a running server.
mockMvc.perform(get("/users/1"))
.andExpect(status().isOk());Stubbing Then Asserting
Stub the mocked service, fire the request, and assert on the response body and status.
when(userService.find(1L))
.thenReturn(new User(1L, "Ada"));
mockMvc.perform(get("/users/1"))
.andExpect(jsonPath("$.name").value("Ada"));Checking Status Codes
Validate error mappings, such as a 404 when the service signals a missing entity.
when(userService.find(9L))
.thenThrow(new NotFoundException());
mockMvc.perform(get("/users/9"))
.andExpect(status().isNotFound());Testing POST with a Body
Send JSON content and verify the controller deserializes and responds correctly.
mockMvc.perform(post("/users")
.contentType("application/json")
.content("{\"name\":\"Ada\"}"))
.andExpect(status().isCreated());JsonPath Assertions
jsonPath expressions let you assert on nested fields, array sizes, and values inside the JSON response.
.andExpect(jsonPath("$.items.length()").value(3))Slice vs Full Context
Use @WebMvcTest for focused, fast web-layer tests. Reserve @SpringBootTest for true end-to-end flows where you want the whole context wired.
Speed Benefits
Because only the web layer loads, these tests start in a fraction of the time of a full-context test, encouraging more thorough controller coverage.
Quick Check
How are service dependencies handled in a @WebMvcTest?
Recap
You learned web-layer slice testing:
@WebMvcTestloads only controllers and web infrastructureMockMvcsimulates HTTP requests without a server@MockBeansupplies mocked services- Assert status and body with
jsonPath
よくある質問
「@WebMvcTestとMockMvcによるWeb層のテスト」レッスンは無料ですか?
はい。「@WebMvcTestとMockMvcによるWeb層のテスト」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Testing Mastery: JUnit, Mockito & Integration Testsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Testing Mastery: JUnit, Mockito & Integration Testsコースには全4レッスンが含まれています。
「@WebMvcTestとMockMvcによるWeb層のテスト」で何を学びますか?
@WebMvcTestとMockMvcを使い、完全なアプリケーションコンテキストを起動せずにSpring Bootのコントローラーを単独でスライステストします。 ブラウザで直接実行するハンズオンコードでTesting Mastery: JUnit, Mockito & Integration Testsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Testing Mastery: JUnit, Mockito & Integration Testsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのTesting Mastery: JUnit, Mockito & Integration Testsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「@WebMvcTestとMockMvcによるWeb層のテスト」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このTesting Mastery: JUnit, Mockito & Integration Testsレッスンでコードを書いて実行できますか?
はい。すべてのTesting Mastery: JUnit, Mockito & Integration Testsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Spring TestContext Framework
- RESTful APIのテスト
- テスト用組み込みデータベース
- @WebMvcTestとMockMvcによるWeb層のテスト