1

Laravel 5.3 with mysql, PHPUnit 5.7.4

When I create a test in PHPUnit with use DatabaseMigrations;, it destroys the data that it queries.

<?php

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

class ThingsTest extends TestCase
{
    use DatabaseMigrations;

    /** @test */
    public function there_are_more_than_1000_things()
    {
        $things = App\Thing::all();

        $this->assertGreaterThan(1000, count($things));
    }

Before I run phpunit, there are lots of things. After running it, mysql says ERROR 1146 (42S02): Table 'database.things' doesn't exist

Any ideas how to stop this?

Mark Karavan
  • 2,654
  • 1
  • 18
  • 38

2 Answers2

2

DatabaseMigrations is a trait and it execs:

  1. before test 'php artisan migrate' // creates your tables, but doesn't seed them
  2. after test 'php artisan migrate:rollback' // remove tables

So, 1st - make sure you're using another database for testing.

2nd - seed with fake data your tables before testing your Things class.

Alternative: use DatabaseTransactions trait instead of DatabaseMigrations. In that case each test activity will be wrapped in a database transaction. After test all your changes will be dropped by transaction's rollback automatically.

Leonid Shumakov
  • 1,319
  • 10
  • 7
1

You can be using a test database with PHPUnit within your Laravel application. Right now your tests are using your main database and will modify existing information.

Please see https://stackoverflow.com/a/35228697/823549 for how to do this.

Community
  • 1
  • 1
1000Nettles
  • 2,314
  • 3
  • 22
  • 31