Laravel 测试 - 我应该在每个测试中创建依赖资源吗?

Laravel Testing - Should I be creating dependant resources in each test?

开始使用 Laravel Spark 6 (Laravel 5.6) 构建新版本,并决定尝试 TDD。

第一次测试很不错,我创建了一个单元测试以确保用户可以创建团队。

(伪代码):

class AddNewTeamTest extends TestCase
{
    /** @test */
    public function admin_can_create_new_team()
    {
        // Create a user account

        $data = [
            // Information for tea,
        ];

        $response = $this->withHeaders([
                'X-Requested-With' => 'XMLHttpRequest',
            ])
            ->actingAs($user)
            ->json('POST', '/api/teams', $data);

        $response
            ->assertStatus(201);
    }

}

在 TDD 风格中使用它是一个很好的过程,但现在我希望能够编写一个测试来向该团队添加一个成员。

似乎倒退了,在这个新测试中,我会 运行 我的第一个测试中的所有代码。有没有办法解决?对于新测试,我需要一个已经创建的用户和团队,然后才能测试将用户添加到该团队..

欢迎任何链接或建议!

您可以使用函数 setUp() 并在其中构建您的环境。 所以你的 class 应该是这样的:

class AddNewTeamTest extends TestCase
    {

    protected  function setUp()
    {

        // Create a user account
        // Create your enviroment, etc.

        $this->actingAs($user)
    }


    /** @test */
    public function admin_can_create_new_team()
    {

        $data = [
            // Information for tea,
        ];

        $response = $this->withHeaders([
                'X-Requested-With' => 'XMLHttpRequest',
            ])
            ->json('POST', '/api/teams', $data);

        $response
            ->assertStatus(201);
    }

    public function testAnother()
    {
        \your next test
    }
}

如果您在接下来的几个案例中需要一个团队,应该在 setUp() 中添加。

此外,您可以将下一次测试所需的时间设为上一次。在这种情况下,您可以 return admin_can_create_new_team() 中的某些内容并在 testAnother()

中作为参数

更多信息: https://phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.test-dependencies