7
6

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 5 years have passed since last update.

【Laravel】テストのsetUp()でエラー「Declaration of…must be compatible with...」

Posted at

状況

UserTest.php
class UserTest extends TestCase
{
    public function setUp()
    {
       //略
    }
}

laravelのphpunitのsetUp()メソッドを上記のように書き、テストを行ったところ
次のようなエラーが出ました。

PHP Fatal error:  Declaration of Tests\Feature\UserTest::setUp() must be compatible with Illuminate\Foundation\Testing\TestCase::setUp(): void in /var/www/tests/Feature/Usertest.php on line 13

エラー内容とその対処

要はテストのsetUp()とIlluminate\Foundation\Testing\TestCase
のsetUp()の返り値が違うということを言われているわけです。

そこでIlluminate\Foundation\Testing\TestCaseクラスを見てみます。

TestCase.php
    protected function setUp(): void
    {
        //略
    }

Illuminate\Foundation\Testing\TestCaseクラスではsetUp()にvoidが返り値として宣言されています。

したがってテストのほうにもvoidのタイプヒンディングをしましょう。

UserTest.php
class UserTest extends TestCase
{
    public function setUp() :void
    {
       //略
    }
}

これで完了。
setUp()が使えるようになると思います。

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?