我有2个测试类,所有测试运行良好。但问题是我不知道如何重用其他测试类方法。我很抱歉是Phpunit的新手,我已经在搜索了,我找不到解决方案。
class A_Test {
public function create_something_1()
{
$this->visit('/a/create')
->type('Name','name')
->press('Submit')
->seeInDatabase('something_1', ['name' => 'Name']);
$data = \App\Models\Something1::first();
return $data;
}
}
class B_Test {
public function create_something_2()
{
// The problem is here, I result of new A_Test always null
$a = (new A_Test)->create_something_1();
$this->visit('/b/create')
->select($a->id, 'something_1')
->type('New Name','name')
->press('Submit')
->seeInDatabase('something_2', ['name' => 'New Name']);
}
}
因此,为了使B_Test工作,我总是像这样
复制A_Test类中的方法class B_Test {
public function create_something_1()
{
$this->visit('/a/create')
->type('Name','name')
->press('Submit')
->seeInDatabase('something_1', ['name' => 'Name']);
$data = \App\Models\Something1::first();
return $data;
}
public function create_something_2()
{
// This is work
$a = $this->create_something_1();
$this->visit('/b/create')
->select($a->id, 'something_1')
->type('New Name','name')
->press('Submit')
->seeInDatabase('something_2', ['name' => 'New Name']);
}
}
答案 0 :(得分:0)
在tests/TestCase.php
文件中,您可以执行此操作:
class TestCase extends Illuminate\Foundation\Testing\TestCase
{
....
protected function create_something_resusable()
{
$this->visit('/a/create')
->type('Name','name')
->press('Submit')
->seeInDatabase('something_1', ['name' => 'Name']);
$data = \App\Models\Something1::first();
return $data;
}
....
}
然后所有测试都可以调用$this->create_something_resusable()
,但请记住在所有测试中扩展TestCase
类。