【问题标题】:using In memory database for laravel 5.5在 laravel 5.5 中使用内存数据库
【发布时间】:2018-09-01 21:33:36
【问题描述】:

我打算在内存数据库中使用 laravel 中的单元测试... 我将此行添加到 phpunit.xml,

<php>
        <env name="APP_ENV" value="testing"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="DB_CONNECTION" value="sqlite" />
        <env name="DB_DATABASE" value=":memory:" />
</php>

这是我在 \tests\Feature\BookTest.php 目录中的 BookTest.php 文件,

<?php

namespace Tests\Feature;

use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class BookTest extends TestCase
{
    use DatabaseMigrations;

    public function test_books_can_be_created()
    {        
        $user = factory(\App\User::class)->create();

        $book = $user->books()->create([
            'name' => 'The hobbit',
            'price' => 10
        ]);

        $found_book = $book->find(1);

        $this->assertEquals($found_book->name, 'The hobbit');
        $this->assertEquals($found_book->price, 10);


    }
}

但是当我们尝试添加 vendor\bin\phpunit 我明白了,

1) 测试\功能\BookTest::test_books_can_be_created Illuminate\Database\QueryException: SQLSTATE[HY000]: General error: 1 no such table: books (SQL: insert into "books" ("name", “price”、“user_id”、“updated_at”、“created_at”)值(霍比特人, 10, 1, 2018-03-23 08:52:26, 2018-03-23 08:52:26))

如果您能帮助我了解如何在 laravel 单元测试中使用内存数据库,那将非常有帮助。

【问题讨论】:

  • 您是否有创建 books 表的迁移?
  • 我不记得了。我也需要迁移吗?如果愚蠢真的很抱歉
  • 是的,您有运行迁移的“使用数据库迁移”

标签: laravel-5


【解决方案1】:

你应该

use RefreshDatabase

所以你的测试应该是这样的

<?php

    namespace Tests\Feature;

    use Tests\TestCase;
    use Illuminate\Foundation\Testing\WithFaker;
    use Illuminate\Foundation\Testing\RefreshDatabase;

    class BookTest extends TestCase
    {
       use RefreshDatabase;

       public function test_books_can_be_created()
       {        
        $user = factory(\App\User::class)->create();

        $book = $user->books()->create([
            'name' => 'The hobbit',
            'price' => 10
        ]);

        $found_book = $book->find(1);

        $this->assertEquals($found_book->name, 'The hobbit');
        $this->assertEquals($found_book->price, 10);
    }
}

来源https://laravel.com/docs/5.5/database-testing#resetting-the-database-after-each-test

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-29
    • 2019-11-27
    • 1970-01-01
    • 2016-04-22
    • 2018-02-13
    • 2018-08-06
    • 2018-07-23
    • 2019-09-19
    相关资源
    最近更新 更多