0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

hintを追加したらtype errorで動かなくなった話

Posted at

概要

laravelでmockeryを用いてunit testを作成中、以下のエラーが出た。

TypeError: Argument 1 passed to App\Http\Services\hoge::__construct() must be an instance of App\Http\Services\hoge or null, instance of Mockery_0__Tests_Feature_hoge given, called in /var/www/hoge/tests/Feature/hogeTest.php on line 277

hoge型かnullのみ受け付けるコードに、Mockery_0__Tests_Feature_hogeを与えたというエラーである。

エラーについて

エラーを起こしたコード

php-テストコード.php
# testServiceで利用するモック
$hogeServiceMock = \Mockery::mock(hogeService::class);
$hogeServiceMock->shouldReceive('gethoge')
                ->andReturn($gethoge);

// テスト対象のサービス、コンストラクタでモックと連携
$testService = new testService($hogeServiceMock);

// テスト対象の関数実行
$response = $testService->issue($testInput);

// テスト結果の確認
$this->assertSame($expected, $response);
php-テスト対象.php
class TestService
{
    /** @var hogeService */
    private $hogeService;
    
    /**
     * AuthController constructor.
     *
     * @param hogeService $hogeService
     */
    public function __construct(hogeService $hogeService)
  {
        $this->hogeService = $hogeService;
    }

    /**
     * テスト対象関数
     *
     * @param string $testInput
     * @return 実行結果の文字列
     */
    public function issue(string $testInput)    
    {
       # いろいろする
    }

エラーの経緯

当初、testService側のhintを記載漏れしており、コードレビューを経てhintを全て追加することに。
すると今まで正常稼働していてたテストコードが上記のtype errorを出力するようになった。

エラーが起きた原因

実はテストコードphp側に記載したhogeServiceへの名前空間(use)にタイポがあり、hogeserviceをうまく呼び出せていなかった。
そのためmockeyが独自型のMockery_0__Tests_Feature_hoge型として動作しており、hintを追加したことでそのエラーに気が付いた。

エラー解消

ちゃんとhogeServiceを呼び出せるように名前空間のtypoを直す。
するとテストコード自体には一切手を入れずとも、hintのエラーが解消する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?