前提
laravelで開発しているサービスのテストコードを書いています
実現したいこと
- テストしたいメソッド内に登場するメソッドをモック化したい
該当のソースコード
テストしたいコードが
php
1class makeUnfollowCheckClass 2{ 3 4 public static function makeUnfollowCheck($twitter_account_id, $target_account_id): bool 5 { 6 $latestTweetCheck = self::latestTweetCheck($twitter, $target_account_id); 7 // 同じクラス内のlatestTweetCheckメソッドが返してくるフラグによって処理が分岐 8 9 return $chk_flg; 10 11 } 12 function latestTweetCheck(TwitterOAuth $twitter, $target_account_id) 13 { 14 return $chk_flg; 15 } 16 17 18 }
書いているテストコード内でlatestTweetCheckメソッドを
モック化し、必ずfalseを返すように実装しているのですが
実際のメソッドを呼び出し、エラーが出てしまっています
php
1 2 $mock = Mockery::mock(makeUnfollowCheckClass::class) 3 ->shouldReceive('latestTweetCheck') 4 ->andReturn(false) 5 ->getMock(); 6 7 $makeUnfollowCheckClass = new makeUnfollowCheckClass($mock); 8 9 $result = $makeUnfollowCheckClass->makeUnfollowCheck($twitter_account_id, $target_account_id); 10
テストしたいメソッド内で呼び出しているメソッドをモック化することは可能でしょうか?
補足情報(FW/ツールのバージョンなど)
Laravel v8.83.23
PHP v7.4.18
PHPUnit 9.5.21
mockery 1.5
回答をいただいて書いたコード
テストしたいコードからstaticを外し
self::を$thisに修正しました
PHP
1class makeUnfollowCheckClass 2{ 3 public function makeUnfollowCheck($twitter_account_id, $target_account_id): bool 4 { 5 $latestTweetCheck = $this->latestTweetCheck($twitter, $target_account_id); 6 } 7 8 return $chk_flg; 9 10 } 11 12 function latestTweetCheck(TwitterOAuth $twitter, $target_account_id) 13 { return $chk_flg; 14 } 15} 16
テストコードの書き方も修正しました
PHP
1 $makeUnfollowCheckClass = Mockery::mock(makeUnfollowCheckClass::class) 2 ->shouldReceive('latestTweetCheck') 3 ->andReturn(false); 4 5 $result = $makeUnfollowCheckClass->makeUnfollowCheck($twitter_account_id, $target_account_id); 6
ErrorException: call_user_func_array() expects parameter 1 to be a valid callback, class 'Mockery\Expectation' does not have a method 'makeUnfollowCheck'
そんなメソッドはないといった意味のエラーが出たので引き続き調べてみます
また、makeUnfollowCheckClassは
App\Console\Commands
配下の
unfollowExecクラスで使用する想定です
PHP
1 $unfollow_check = app(makeUnfollowCheckClass::class)->makeUnfollowCheck($twitter, $targetId); 2

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/08/29 15:00