我曾经使用 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 5.8 在
setUp
方法的返回类型中添加了 void typehint。public function setUp(): void
{
// you should also call parent::setUp() to properly boot
// the Laravel application in your tests
$this->instance = new MyService;
}
注意函数参数后面的
: void
用于说明该函数的返回类型
这就是我所做的,它有帮助
/**
* 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
感谢您为 Stack Overflow 提供答案!
请务必回答问题。提供详细信息并分享您的研究! 但要避免……
寻求帮助、澄清或回应其他答案。 根据意见作出陈述;用参考资料或个人经验来支持它们。 要了解更多信息,请参阅我们关于撰写精彩答案的提示。