laravel - 在 Laravel PHPUnit 测试中使用内存 SQLite

标签 laravel sqlite phpunit laravel-5.6 in-memory-database

我正在尝试让 Laravel 项目在我的新工作中运行。离开的开发者在移交文档中没有具体说明如何让代码运行起来,其他人也不知道。

SQLite 数据库是使用 :memory: 创建的,php artisan migrate 可以正常工作。

...
Migrating: 2016_06_01_000004_create_oauth_clients_table
Migrated:  2016_06_01_000004_create_oauth_clients_table
...

特征(标准 Laravel 代码)中的方法 beginDatabaseTransaction() 正在执行,但之后没有任何表存在。就好像正在创建数据库但没有执行迁移。

<?php

namespace Illuminate\Foundation\Testing;

trait DatabaseTransactions
{
    /**
     * Handle database transactions on the specified connections.
     *
     * @return void
     */
    public function beginDatabaseTransaction()
    {
        $database = $this->app->make('db');

        foreach ($this->connectionsToTransact() as $name) {
            $database->connection($name)->beginTransaction();
        }

        $this->beforeApplicationDestroyed(function () use ($database) {
            foreach ($this->connectionsToTransact() as $name) {
                $connection = $database->connection($name);

                $connection->rollBack();
                $connection->disconnect();
            }
        });
    }

测试代码(最后显示的指令失败):

<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Laravel\Passport\ClientRepository;

class PassportTest extends TestCase
{
    use DatabaseTransactions;

    public function test_basic_oauth_token_authentication(){
      $clientRepository = new ClientRepository();
      $client = $clientRepository->createPersonalAccessClient(
          null, 'Test Personal Access Client', $this->baseUrl
      );

命令行:

vendor/bin/phpunit tests/Feature/PassPortTest

错误消息:

Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: oauth_clients
Caused by  
Doctrine\DBAL\Driver\PDOException: SQLSTATE[HY000]: General error: 1 no such table: oauth_clients
Caused by
PDOException: SQLSTATE[HY000]: General error: 1 no such table: oauth_clients

如何确保表已作为每个测试的一部分创建?

最佳答案

使用 RefreshDatabase 特征而不是 DatabaseTransactions 特征(如果您尝试在同一个类中使用这两个特征,它们会发生冲突)。

查看有关resetting the database after each test的文档.

关于laravel - 在 Laravel PHPUnit 测试中使用内存 SQLite,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51948267/

相关文章:

php - Laravel 查询构建器不适用于子查询中的 where 子句

javascript - getstream.io 获取 CORS 请求被拒绝 : https://api. stream-io-api.com/api/v1.0/feed/user

c# - 不能在 Dapper 查询中使用自定义类型作为参数插入 SQLite 数据库

android - 查询FTS表MIN

ruby-on-rails - 为什么 Rails 3 Gemfile 中同时引用了 sqlite3 和 sqlite3-ruby gem?

unit-testing - Laravel 5.4;如何从 Laravel 包运行单元测试?

phpunit:运行单个测试时通过,运行所有测试时失败

php - 能够绕过图像验证

javascript - 使用ajax更改页面时重新初始化javascript函数

unit-testing - 测试用例的 PHPUnit 设置和拆卸