【问题标题】:How to use the method setup from PHPUnit in Laravel 5.8如何在 Laravel 5.8 中使用 PHPUnit 的方法设置
【发布时间】:2019-12-26 04:23:45
【问题描述】:

我曾经使用 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 );
    }
}


这不起作用:

<?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 );
    }
}

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

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

【问题讨论】:

    标签: laravel unit-testing phpunit


    【解决方案1】:

    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;
    }
    

    注意函数参数后的: void 表示该函数的返回类型

    【讨论】:

      【解决方案2】:

      这就是我所做的,它有帮助

      /**
           * Set up the test
           */
          public function setUp(): void
          {
              parent::setUp();
              $this->faker = Faker::create();
          }
      
          /**
           * Reset the migrations
           */
          public function tearDown(): void
          {
              $this->artisan('migrate:reset');
              parent::tearDown();
          }
      

      没有在函数中声明返回类型为 void

      【讨论】:

        猜你喜欢
        • 2013-06-19
        • 2020-02-17
        • 1970-01-01
        • 2017-03-05
        • 2016-02-18
        • 2023-03-11
        • 1970-01-01
        • 2020-02-09
        • 1970-01-01
        相关资源
        最近更新 更多