abkrim
abkrim

Reputation: 3692

RuntimeException: A facade root has not been set

I am trying to develop on a fork of another package a utility to work with the schemas of the data bases of a Laravel application.

In my development I want to use Tests since the previous one had nothing. Although the package works perfectly integrated in an application with Laravel 6.X when I try to test the package it fails me

<?php

namespace Abkrim\DbSchema\Tests;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use PHPUnit\Framework\TestCase;
use Faker\Factory as Faker;

class DbSchemaTest extends TestCase
{
    /** @test */
    function it_can_access_the_database()
    {
       $faker = Faker::create();

       $user = DB::table('users')->insert([
           'email' => $faker->unique()->email,
           'name' => $faker->unique()->name,
           'password' => $faker->password(10),
           'rememberToken' => $faker->md5
       ]);
    }
}

If try running test

vendor/bin/phpunit --filter DbSchemaTest

1) Abkrim\DbSchema\Tests\DbSchemaTest::it_can_access_the_database
RuntimeException: A facade root has not been set.

/home/abkrim/Sites/db-schema/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:236
/home/abkrim/Sites/db-schema/tests/DbSchemaTest.php:17

Upvotes: 3

Views: 2351

Answers (1)

abkrim
abkrim

Reputation: 3692

A simple forgetfulness. To test Laravel packages outside Laravel, it is necessary to extend the Orchestra TestCase instead of PHPUnit

Correct code is

<?php

namespace Abkrim\DbSchema\Tests;

use Abkrim\DbSchema\DbSchema;
use Abkrim\DbSchema\DbSchemaServiceProvider;
use Abkrim\DbSchema\DbSchemaFacade;
use Faker\Factory as Faker;
use Illuminate\Support\Facades\DB;
use Orchestra\Testbench\TestCase;

class DbSchemaTest extends TestCase
{
    protected function getPackageProviders($app)
    {
        return [
            DbSchemaServiceProvider::class
        ];
    }

    protected function getPackageAliases($app)
    {
        return [
            'DbSchema' => DbSchema::class
        ];
    }

    protected function getEnvironmentSetUp($app)
    {
        include_once __DIR__ . '/../database/migrations/create_users_table.php.stub';

        (new \CreateUsersTable)->up();
    }

    /** @test */
    function it_can_access_the_database()
    {
        $faker = Faker::create();
        $mail = '[email protected]';

        DB::table('users')->insert([
           'email' => $mail,
           'name' => $faker->unique()->name,
           'password' => $faker->password(10),
           'remember_token' => $faker->md5
        ]);

        $user = DB::table('users')->first();

        $this->assertSame($user->email, $mail);
    }
}

Upvotes: 2

Related Questions