DEV Community

Dimitrios Desyllas
Dimitrios Desyllas

Posted on

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

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()
   {
     /**
      *

Top comments (3)

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
 
roelofjanelsinga profile image
Roelof Jan Elsinga

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