在内存数据库中使用laravel 5.5

时间:2018-03-23 08:57:08

标签: laravel-5

我打算在内存数据库中使用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)测试\ Feature \ BookTest :: test_books_can_be_created   Illuminate \ Database \ QueryException:SQLSTATE [HY000]:一般错误:1没有这样的表:books(SQL:insert into&#34; books&#34;(&#34; name&#34;,   &#34;价格&#34;,&#34; user_id&#34;,&#34; updated_at&#34;,&#34; created_at&#34;)值(霍比特人,   10,1,2018-03-23 08:52:26,2018-03-23 08:52:26))

如果你可以帮助我如何在laravel单元测试中使用内存数据库,那将会很有帮助。

1 个答案:

答案 0 :(得分:2)

您应该

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