- 今回はKahlanのテストカバレッジをk1LoW/octocovを利用して計測してみます。
目次
環境
- Laravel 11 / PHP 8.3
- Kahlan 5.2.6
- Mac OS(Sonoma 14.1)
準備
- 前回のテストを利用
- k1LoW/octocovをインストール
brew install k1LoW/tap/octocov
# .octocov.yml作成
$ octocov init
- XDebugをインストール
$ pecl install xdebug
# php.iniにextension項目を追加
$ vi /usr/local/etc/php/8.3/php.ini
zend_extension=xdebug.so
xdebug.mode=coverage
# 保存する
テストカバレッジの出力
# clover形式でカバレッジレポートを出力
$ vendor/bin/kahlan --reporter=verbose --src=app --clover=coverage.xml
Cannot load Xdebug - it was already loaded
_ _
/\ /\__ _| |__ | | __ _ _ __
/ //_/ _` | '_ \| |/ _` | '_ \
/ __ \ (_| | | | | | (_| | | | |
\/ \/\__,_|_| |_|_|\__,_|_| |_|
The PHP Test Framework for Freedom, Truth and Justice.
src directory : /Users/hoge/factory/blog/kahlan/app
spec directory : /Users/hoge/factory/blog/kahlan/spec
SampleController Test
getUserInfo
条件:ユーザーIDが不正
✓ it 結果:バリデーションエラー
条件:ユーザーIDが指定された時
✓ it 結果:ユーザーが存在しなかった
✓ it 結果:ユーザーが存在した
Expectations : 6 Executed
Specifications : 0 Pending, 0 Excluded, 0 Skipped
Passed 3 of 3 PASS in 0.359 seconds (using 34MB)
Coverage Summary
----------------
Total: 100.00% (7/7)
Coverage collected in 0.001 seconds
# octocovでカバレッジ表示
$ octocov
feature/kahlan_octocov
(fe0142b)
------------------------------------------------------
Coverage 100.0%
Code to Test Ratio 1:0.6
# カバレッジファイル一覧
$ ctocov ls-files
100.0% [5/5] app/Http/Controllers/SampleController.php
100.0% [2/2] app/Models/User.php
# 指定ファイルのカバレッジ個別表示
$ octocov view app/Http/Controllers/SampleController.php
1 <?php
2
3 namespace App\Http\Controllers;
4
5 use App\Models\User;
6 use Illuminate\Http\JsonResponse;
7 use Illuminate\Http\Request;
8 use Illuminate\Support\Facades\Validator;
9 use Illuminate\Validation\ValidationException;
10
11 /**
12 * Class SampleController
13 * @package App\Http\Controllers
14 */
15 class SampleController extends Controller
16 {
17 /**
18 * ユーザー情報取得
19 * @param Request $request
20 * @return JsonResponse
21 * @throws ValidationException
22 */
23 public function getUserInfo(Request $request): JsonResponse
24 {
25 // パラメータバリデーション
26 $validator = Validator::make($request->all(), [
27 'userId' => 'required|integer'
28 4 ]);
29
30 // バリデーション失敗
31 if ($validator->fails()) {
32 2 return response()->json(['error' => 'Request format error'], 400);
33 }
34
35 // 指定ユーザー情報取得
36 2 $user = User::find($validator->validated()['userId']);
37 if (!$user) {
38 2 return response()->json(['error' => 'User not found'], 404);
39 }
40 2 return response()->json($user);
41 }
42 }
まとめ
- kahlanで出力したカバレッジレポートをoctocovで簡単に可視化できた。
- octocovは様々なカバレッジレポートの形式に対応していてGitHubActionsなどとの連携も出来たりと使うと楽しそう。