如何在 Laravel 5.8 中使用 PHPUnit 的方法设置

Sau*_*pos 6 phpunit unit-testing laravel

我曾经使用 PHPUnit 的方法设置来为我的测试方法创建一个实例。但是在 Laravel 5.8 中我做不到

我已经尝试了两种方法,它的工作原理是为每个方法创建一个实例,如下所示。

这有效:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Service\MyService;

class MyServiceTest extends TestCase
{
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function testInstanceOf()
    {
        $myService = new MyService;
        $this->assertInstanceOf( 'App\Service\MyService' , $myService );
    }
}


Run Code Online (Sandbox Code Playgroud)

这不起作用:

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\Service\MyService;

class MyServiceTest extends TestCase
{

    private $instance;

    function setUp(){    
      $this->instance = new MyService;
    }
    /**
     * A basic unit test example.
     *
     * @return void
     */
    public function testInstanceOf()
    {
        $myService = $this->instance;
        $this->assertInstanceOf( 'App\Service\MyService' , $myService );
    }
}

Run Code Online (Sandbox Code Playgroud)

以下错误消息显示在控制台中:

PHP Fatal error:  Declaration of Tests\Unit\MyServiceTest::setUp() must be compatible with Illuminate\Foundation\Testing\TestCase::setUp(): void in /home/myproject/tests/Unit/MyServiceTest.php on line 10

Run Code Online (Sandbox Code Playgroud)

mde*_*exp 10

Laravel 5.8 在setUp方法的返回类型中添加了 void 类型提示。
所以你必须像这样声明:

public function setUp(): void
{
    // you should also call parent::setUp() to properly boot
    // the Laravel application in your tests
    $this->instance = new MyService;
}
Run Code Online (Sandbox Code Playgroud)

需要注意: void函数参数后声明,函数的返回类型