DEV Community

loading...

How I can have on each phpunit test specific tearDown logic?

pcmagas profile image Dimitrios Desyllas ・1 min read

Guys can you tell me how I can have per-test tearDown logic?

On my phpunit tests I need to run a cleanup functionality for each test seperately for example:

use PHPUnit\Framework\TestCase;

use MyApp\Database\DatabaseEntryDataGenerator;
use MyApp\Database\Record\User;
use MyApp\Database\Record\Emails;

class MyEmailTest extends TestCase
{

   public function testEmailValid()
   {
     /**
      * @var EmailEntries
      */
     $emails=DatabaseEntryDataGenerator::table(EmailEntries::TABLE)->generate();

     //Do test
    $emails->delete();
   }

   public function testEmailValidOnUser()
   {
     /**
      *

Discussion

pic
Editor guide
Collapse
shimphillip profile image
Phillip Shim

Hello op, this is not related to the post but I suggest you change your profile picture. That is a picture of the rising sun flag which represents Japan’s imperialism era. It is equivalent to the Nazi flag and is very offensive to many other Asian countries. Regards.

Collapse
robdwaller profile image
Rob Waller

Another approach is to run these tests against an in memory database which rebuilds when required.

Also assuming these tests interact with the database I'd classify them as integration tests so I personally wouldn't have them run as part of my unit test suite. I'd have them run as separate process further up my CI pipeline.

Collapse
bpedroza profile image
Bryan

I don't know what you're using for the DB stuff, but an easy way to handle this is to open a transaction in the setup method, then rollback tear down method.

Collapse
roelofjanelsinga profile image
Roelof Jan Elsinga

Yes, been doing this for years! Definitely the easiest way 👍