Search code examples
phpunit-testinglaravel-8laravel-seeding

laravel 8: how to use seeder in unit test


im trying to get the data after seeding a simple json to database. Here's the code:

<?php

namespace Tests\Unit;

use PHPUnit\Framework\TestCase;
use Database\Seeders\TagsSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;

class TagTest extends TestCase
{
    use RefreshDatabase;

    public function test_GetTags()
    {
        $this->seed(TagsSeeder::class);
        $response = $this->get('/api/tags')->seeJson(["name" => "mytags"]);
        $response->assertStatus(200);
    }
}

coding above based on documentation here: database testing but when i run the test with command

php artisan test ./tests/Unit/TagTest.php

it's return error below:

Call to undefined method Tests\Unit\TagTest::seed()

Solution

  • Use this class :

    use Tests\TestCase;
    

    Instead of this :

    use PHPUnit\Framework\TestCase;
    

    and extend TagTest from it.

    currently you're extending from PHPUnit\Framework\TestCase and thats the reason why seeders not available because its PHPUnit test class not Laravel test class