在 Laravel 单元测试期间保存变量

Dmi*_*try 2 php phpunit unit-testing laravel

变量$this->id在另一个函数中不可见testExemple

\n\n

如果我将此变量传递给不在 \xe2\x80\x9ctest\xe2\x80\x9d 上启动的普通函数,而不是测试函数,则一切都会正常。

\n\n

我能以某种方式解决这个问题吗?

\n\n
class LoginTest extends TestCase\n{\n    protected $id;\n    public function testLogin()\n    {\n        $response = $this->json('post', 'auth/login', \n            ['email' => 'admin@mail.com', 'password' => '12345678'])\n            ->assertJsonStructure(['data' => ['id', 'name', 'email']]);\n\n        $response->assertStatus(201);\n\n        $userData = $response->getContent();\n        $userData = json_decode($userData, true);\n        $this->id = $userData['data']['id'];\n    }\n    public function testExemple()\n    {\n        echo($this->id);\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

apo*_*fos 7

据我所知,每个测试都是独立运行的,如果您想将数据从一个测试传递到另一个测试,您可以使用@depends如下所示的文档注释:

class LoginTest extends TestCase
{
    public function testLogin()
    {
        $response = $this->json('post', 'auth/login', 
            ['email' => 'admin@mail.com', 'password' => '12345678'])
            ->assertJsonStructure(['data' => ['id', 'name', 'email']]);

        $response->assertStatus(201);

        $userData = $response->getContent();
        $userData = json_decode($userData, true);
        return $userData['data']['id']; //Return this for the dependent tests
    }

    /**
      * @depends testLogin
      */
    public function testExample($id)
    {
        echo($id);
    }
}
Run Code Online (Sandbox Code Playgroud)

然而,您可能遇到的问题是,虽然$id有一个值,但用户在此测试期间实际上并未登录,因为其他所有内容(例如会话)都将被清除。

为了确保用户已登录,您需要模拟用户登录,如下所示:

    public function testExample()
    {
        $this->actingAs(User::where('email', 'admin@mail.com')->first()); //User now logged in
        echo(\Auth::id());
    }
Run Code Online (Sandbox Code Playgroud)

这可确保用户登录并解耦测试。