unit-test-controller-layer
MockMvcと@WebMvcTestを使用してRESTコントローラーのユニットテストを行うパターンを提供します。リクエスト/レスポンスのマッピング、バリデーション、例外処理、HTTPステータスコードを検証するコントローラーテストを生成します。APIエンドポイントのテスト、Spring MVCテスト、モックHTTPリクエスト、またはコントローラーレイヤーのユニットテストとして、Webレイヤーのエンドポイントを独立してテストする際に使用してください。
description の原文を見る
Provides patterns for unit testing REST controllers using MockMvc and @WebMvcTest. Generates controller tests that validates request/response mapping, validation, exception handling, and HTTP status codes. Use when testing web layer endpoints in isolation for API endpoint testing, Spring MVC tests, mock HTTP requests, or controller layer unit tests.
SKILL.md 本文
MockMvcを使用したREST コントローラーのユニットテスト
概要
MockMvcを使用して@RestControllerおよび@Controllerクラスをユニットテストするためのパターンを提供します。リクエスト/レスポンス処理、HTTPステータスコード、リクエストパラメーターバインディング、バリデーション、コンテンツネゴシエーション、レスポンスヘッダー、およびモックされたサービス依存関係での例外処理をカバーしています。
使用するタイミング
用途:コントローラーテスト、APIエンドポイントテスト、Spring MVCテスト、モックHTTPリクエスト、Webレイヤーエンドポイントのユニットテスト、REST コントローラーの分離検証。
使用方法
- スタンドアロンMockMvcをセットアップ:
MockMvcBuilders.standaloneSetup(controller)で分離テストを実施 - サービス依存関係をモック: すべてのサービスに
@Mockを、コントローラーに@InjectMocksを使用 - HTTPメソッドをテスト: GET、POST、PUT、PATCH、DELETE を適切なステータスコードでテスト
- レスポンスを検証: JSONPathアサーションでJSON、コンテンツマッチャーでボディを検証
- バリデーションをテスト: 無効な入力を送信し、エラー詳細を含む400ステータスを検証
- エラーをテスト: 適切な条件で404、400、401、403、500を検証
- ヘッダーを検証: リクエスト(Authorization)とレスポンスヘッダーの両方
- コンテンツネゴシエーションをテスト: 異なるAcceptおよびContent-Typeヘッダー
バリデーションワークフロー
テスト実行 → 失敗時:.andDo(print())を追加 → 実際の値と期待値を確認 → アサーションを修正
例
Maven / Gradle 依存関係
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
基本パターン:GETエンドポイント
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@ExtendWith(MockitoExtension.class)
class UserControllerTest {
@Mock
private UserService userService;
@InjectMocks
private UserController userController;
private MockMvc mockMvc;
@BeforeEach
void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(userController).build();
}
@Test
void shouldReturnAllUsers() throws Exception {
List<UserDto> users = List.of(new UserDto(1L, "Alice"), new UserDto(2L, "Bob"));
when(userService.getAllUsers()).thenReturn(users);
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id").value(1))
.andExpect(jsonPath("$[0].name").value("Alice"));
verify(userService, times(1)).getAllUsers();
}
@Test
void shouldReturn404WhenUserNotFound() throws Exception {
when(userService.getUserById(999L))
.thenThrow(new UserNotFoundException("User not found"));
mockMvc.perform(get("/api/users/999"))
.andExpect(status().isNotFound());
verify(userService).getUserById(999L);
}
}
POST:リソース作成
@Test
void shouldCreateUserAndReturn201() throws Exception {
UserDto createdUser = new UserDto(1L, "Alice", "alice@example.com");
when(userService.createUser(any())).thenReturn(createdUser);
mockMvc.perform(post("/api/users")
.contentType("application/json")
.content("{\"name\":\"Alice\",\"email\":\"alice@example.com\"}"))
.andExpect(status().isCreated())
.andExpect(jsonPath("$.id").value(1))
.andExpect(jsonPath("$.name").value("Alice"));
verify(userService).createUser(any(UserCreateRequest.class));
}
PUT:リソース更新
@Test
void shouldUpdateUserAndReturn200() throws Exception {
UserDto updatedUser = new UserDto(1L, "Updated");
when(userService.updateUser(eq(1L), any())).thenReturn(updatedUser);
mockMvc.perform(put("/api/users/1")
.contentType("application/json")
.content("{\"name\":\"Updated\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.name").value("Updated"));
verify(userService).updateUser(eq(1L), any());
}
DELETE:リソース削除
@Test
void shouldDeleteUserAndReturn204() throws Exception {
doNothing().when(userService).deleteUser(1L);
mockMvc.perform(delete("/api/users/1"))
.andExpect(status().isNoContent());
verify(userService).deleteUser(1L);
}
クエリパラメーター
@Test
void shouldFilterUsersByName() throws Exception {
when(userService.searchUsers("Alice")).thenReturn(List.of(new UserDto(1L, "Alice")));
mockMvc.perform(get("/api/users/search").param("name", "Alice"))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].name").value("Alice"));
verify(userService).searchUsers("Alice");
}
パス変数
@Test
void shouldGetUserByIdFromPath() throws Exception {
when(userService.getUserById(123L)).thenReturn(new UserDto(123L, "Alice"));
mockMvc.perform(get("/api/users/{id}", 123L))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value(123));
}
バリデーションエラー(400)
@Test
void shouldReturn400WhenRequestBodyInvalid() throws Exception {
mockMvc.perform(post("/api/users")
.contentType("application/json")
.content("{\"name\":\"\"}"))
.andExpect(status().isBadRequest())
.andExpect(jsonPath("$.errors").isArray());
}
レスポンスヘッダー
@Test
void shouldReturnCustomHeaders() throws Exception {
when(userService.getAllUsers()).thenReturn(List.of());
mockMvc.perform(get("/api/users"))
.andExpect(status().isOk())
.andExpect(header().exists("X-Total-Count"))
.andExpect(header().string("X-Total-Count", "0"));
}
Authorizationヘッダー
@Test
void shouldRequireAuthorizationHeader() throws Exception {
mockMvc.perform(get("/api/users"))
.andExpect(status().isUnauthorized());
mockMvc.perform(get("/api/users").header("Authorization", "Bearer token"))
.andExpect(status().isOk());
}
コンテンツネゴシエーション
@Test
void shouldReturnJsonWhenAcceptHeaderIsJson() throws Exception {
when(userService.getUserById(1L)).thenReturn(new UserDto(1L, "Alice"));
mockMvc.perform(get("/api/users/1").accept("application/json"))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json"));
}
ベストプラクティス
- 分離コントローラーテストに
standaloneSetup()を使用 - サービスレイヤーをモック — コントローラーはHTTPを処理、サービスはビジネスロジックを処理
- モックインタラクションを検証:
verify(service).method(args) - 成功パスとエラーシナリオ(404、400、500)の両方をテスト
- JSONアサーションに
jsonPath()を使用 - テストメソッドごとに1つの焦点を絞ったアサーション
制約と警告
- コントローラーテストはHTTP処理のみを検証 — 完全なリクエストフローではありません
standaloneSetup()は完全なコンテキストなしに@Validatedをサポートしない可能性があります- JsonPathはレスポンスボディに有効なJSONが必要です
@PreAuthorize/@Securedは追加セットアップが必要 — セキュリティテストを別途検討してください- ファイルアップロードには
MockMultipartFileが必要です
参考資料
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- giuseppe-trisciuoglio
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/giuseppe-trisciuoglio/developer-kit / ライセンス: MIT
関連スキル
doubt-driven-development
重要な判断はすべて、本番環境への展開前に新しい視点から対抗的レビューを実施します。速度より正確性が重要な場合、不慣れなコードを扱う場合、本番環境・セキュリティに関わるロジック・取り消し不可の操作など影響度が高い場合、または後でバグを修正するよりも今検証する方が効率的な場合に活用してください。
apprun-skills
TypeScriptを使用したAppRunアプリケーションのMVU設計に関する総合的なガイダンスが得られます。コンポーネントパターン、イベントハンドリング、状態管理(非同期ジェネレータを含む)、パラメータと保護機能を備えたルーティング・ナビゲーション、vistestを使用したテストに対応しています。AppRunコンポーネントの設計・レビュー、ルートの配線、状態フローの管理、AppRunテストの作成時に活用してください。
desloppify
コードベースのヘルスチェックと技術負債の追跡ツールです。コード品質、技術負債、デッドコード、大規模ファイル、ゴッドクラス、重複関数、コードスメル、命名規則の問題、インポートサイクル、結合度の問題についてユーザーが質問した場合に使用してください。また、ヘルススコアの確認、次の改善項目の提案、クリーンアップ計画の作成をリクエストされた際にも対応します。29言語に対応しています。
debugging-and-error-recovery
テストが失敗したり、ビルドが壊れたり、動作が期待と異なったり、予期しないエラーが発生したりした場合に、体系的な根本原因デバッグをガイドします。推測ではなく、根本原因を見つけて修正するための体系的なアプローチが必要な場合に使用してください。
test-driven-development
テスト駆動開発により実装を進めます。ロジックの実装、バグの修正、動作の変更など、あらゆる場面で活用できます。コードが正常に動作することを証明する必要がある場合、バグ報告を受けた場合、既存機能を修正する予定がある場合に使用してください。
incremental-implementation
変更を段階的に実施します。複数のファイルに影響する機能や変更を実装する場合に使用してください。大量のコードを一度に書こうとしている場合や、タスクが一度では完結できないほど大きい場合に活用します。