0

Estou criando testes unitários no meu sistema, utilizando SQLite (em memória), mas sempre que eu tento executá-los, eles retornam o erro:

1) Tests\Unit\UserTest::testUserCreate
Symfony\Component\Console\Exception\CommandNotFoundException: The command "migrate:fresh" does not exist.

/var/www/html/vendor/laravel/framework/src/Illuminate/Console/Application.php:178
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Console/Kernel.php:264
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:136
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/PendingCommand.php:220
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithConsole.php:56
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/DatabaseMigrations.php:16
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:109
/var/www/html/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestCase.php:72
/var/www/html/tests/TestCase.php:24

As classes utilizadas para fazer os testes estão assim:

UserTest.php

<?php

namespace Tests\Unit;

use App\Domains\UserDomain;
use App\Models\User;
use Tests\TestCase;

class UserTest extends TestCase
{

    private $userDomain;

    public function __construct()
    {
        parent::setUp();
        $this->userDomain = app('App\Domains\UserDomain');
    }

    public function testUserCreate()
    {
        $userFactory = factory(User::class)->make();

        $userData = [
            'name' => $userFactory->name,
            'email' => $userFactory->email,
            'password' => '123456',
        ];

        $user = $this->userDomain->create($userData);

        $this->assertInstanceOf(User::class, $userFactory);
        $this->assertEquals($userData['name'], $userFactory->name);
        $this->assertEquals($userData['email'], $userFactory->email);
        $this->assertTrue(!empty($user->password));

    }
}

OBS: O "UserDomain" é a camada responsável pelas regras de negócio relacionadas ao usuário. A função "create" cria o model do usuário e insere ele no banco de dados (basicamente um User::create(['name' => name, 'email' => email, 'password' => password]));

TestCase.php

<?php
namespace Tests;

use Faker\Factory as Faker;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

/**
 * Class TestCase
 * @package Tests
 * @runTestsInSeparateProcesses
 * @preserveGlobalState disabled
 */
abstract class TestCase extends BaseTestCase
{
    use CreatesApplication, DatabaseTransactions, DatabaseMigrations;
    protected $faker;
    /**
     * Set up the test
     */
    public function setUp(): void
    {
        parent::setUp();
        $this->faker = Faker::create();
    }
    /**
     * Reset the migrations
     */
    public function tearDown(): void
    {
        $this->artisan('migrate:reset');
        parent::tearDown();
    }
}

phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="testing" force="true"/>
        <env name="CACHE_DRIVER" value="array" force="true"/>
        <env name="SESSION_DRIVER" value="array" force="true"/>
        <env name="QUEUE_DRIVER" value="sync" force="true"/>
        <env name="DB_CONNECTION" value="sqlite" force="true"/>
        <env name="DB_DATABASE" value=":memory:" force="true"/>
        <env name="API_DEBUG" value="false" force="true"/>
        <env name="MAIL_DRIVER" value="log" force="true"/>
        <ini name="memory_limit" value="512M" />
    </php>
</phpunit>

1 Resposta 1

0

Tente usar o trait "RefreshDatabase" do Laravel.

<?php

namespace Tests\Unit;

use App\Domains\UserDomain;
use App\Models\User;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;

class UserTest extends TestCase
{
    use RefreshDatabase;

    private $userDomain;

    ...

}

Referência: Resetting The Database After Each Test

1
  • Fiz essa alteração, mas continuo tendo problemas: 1) Tests\Unit\UserTest::testUserCreate ReflectionException: Class config does not exist (não consegui colocar o stack trace completo por limitação de caracteres dos comentários) Commented 24/04/2019 às 14:11

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .