1

我的 Laravel 应用程序中有以下测试文件:

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ApiAuthControllerTest extends TestCase{

    use DatabaseTransactions;

    public function testLogin(){

        // Test login success
        $response = $this->json('POST', '/login', array(
            'email' => 'hello@yahoo.com',
            'password' => 'sometext'
        ))->decodeResponseJson();
        return $response['token'];

    }

   /**
     * @depends testLogin
     */
    public function testLogout($token){

        // Test logout success
        $this->json('DELETE', '/logout', array(
            'token' => $token
        ))->assertReponseStatus(200);

    }

}

我正在使用DatabaseTransactions该类将我的测试包装为事务,因此它们不会写入我的数据库。我注意到使用这个类会将我的类中的每个单独的测试包装为一个事务。

我想将整个类包装为一个事务。在上面的示例中,当我测试注销请求时,我需要从登录请求生成的令牌在数据库中持久存在。

我将如何使用 Laravel 做到这一点?

4

1 回答 1

2

不幸的是,我不相信这是可能的。setUpLaravel 在/上刷新应用实例tearDown。在 PHPUnit 中,这些函数在每个测试方法中运行。因此,使用事务意味着测试方法之间不会有持久性。

但是,您可以在testLogout测试中再次生成令牌。由于您的注销测试依赖于存在的令牌,因此该方法本质上没有任何问题。

于 2018-02-12T19:10:43.580 回答