【问题标题】:Laravel 5 PHPUnit Testing - Wrapping All Tests Within a Controller Into a Single TransactionLaravel 5 PHPUnit 测试 - 将控制器中的所有测试包装到单个事务中
【发布时间】:2018-07-22 22:47:24
【问题描述】:

我的 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 做到这一点?

【问题讨论】:

    标签: laravel laravel-5 phpunit laravel-5.2 laravel-testing


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2017-11-29
      • 1970-01-01
      • 2016-06-04
      • 2015-10-14
      • 2015-03-24
      • 2015-06-10
      相关资源
      最近更新 更多