如何在Laravel 5.8中使用PHPUnit中的方法设置 [英] How to use the method setup from PHPUnit in Laravel 5.8

查看:316
本文介绍了如何在Laravel 5.8中使用PHPUnit中的方法设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I used to use the method setup of PHPUnit to create a instance for my test methods. But in Laravel 5.8 I can't do it

我已经尝试了两种方法,并且它的工作原理使每个方法的实例如下所示.

I've tried both ways, and it's works makes an instance per method how showed below.

这有效:

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

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

This error message below show in console:

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 5.8在setUp方法的返回类型中添加了void typehint. 因此,您必须像这样声明:

Laravel 5.8 added the void typehint to the return type of the setUp method.
So you have to declare that like this:

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

请注意在函数参数后的: void,以声明该函数的返回类型

Note the : void after the function arguments to state the return type of that function

这篇关于如何在Laravel 5.8中使用PHPUnit中的方法设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆