Toma Tomov
Toma Tomov

Reputation: 1654

Reset database at the end of test

I want to reset my test database after each test but somehow can't find a way to do it. Can delete the data added in each test but I am pretty sure this is not the correct approach. What I have as test is simply this:

<?php

declare(strict_types=1);

namespace Tests\Unit\Entity;

use App\Repository\UserRepository;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
use Tests\Shared\Factory\UserFactory;


final class UserTest extends KernelTestCase
{
    public function testGettersReturnCorrectData(): void
    {
        self::bootKernel();

        /** @var UserRepository $repo */
        $repo = self::getContainer()->get(UserRepository::class);
        
        $user = UserFactory::createUser();
        $repo->add($user, true);
        $this->assertSame($user->getEmail(), UserFactory::EMAIL);
        $this->assertSame($user->getPassword(), UserFactory::PASSWORD);
        $this->assertSame($user->getReferralCode(), UserFactory::REFERRAL_CODE);
    }
}

The newly created user stays in the db. I am using MySQL test db because my production db will be MySQL and don't want to reach some corner cases because of the different dbs. This is my env.test if needed.

# define your env variables for the test env here
KERNEL_CLASS='App\Kernel'
APP_SECRET='$ecretf0rt3st'
SYMFONY_DEPRECATIONS_HELPER=999999
PANTHER_APP_ENV=panther
PANTHER_ERROR_SCREENSHOT_DIR=./var/error-screenshots
DATABASE_URL="mysql://root:[email protected]:3306/api?serverVersion=5.7&charset=utf8mb4"

Upvotes: 2

Views: 3694

Answers (2)

GusDeCooL
GusDeCooL

Reputation: 5758

Maybe try this package https://github.com/dmaicher/doctrine-test-bundle Disclaimer: I haven't test it myself


I remember done similar things using setup and teardown in PHPUnit and using transactional feature.

If I found the code or recreate it, I will let you know or update this post.

Upvotes: 1

Toskan
Toskan

Reputation: 14931

by the love of god, follow @craigh 's advice and look into foundry

https://symfony.com/bundles/ZenstruckFoundryBundle/current/index.html#database-reset

they do exactly that, and actually provide good stuff so you can build your test database inside each test case. Symfony's fixtures solution, in my subjective opinion, is worse than foundry.

Upvotes: -1

Related Questions