Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete from database after tests insert data using PHPUnit?

I want to delete every new entry made with the tests in order to make it possible to run it again (both on the CI build or manually) without having to manually delete the database entries made with the previous run of the tests. I have found the tearDown() and tearDownAfterClass() but it seems to be useful only for connecting/disconnecting the link with the database. Can I use it to delete the entries made with the tests?

like image 377
Masamune Avatar asked Jan 18 '26 12:01

Masamune


1 Answers

Yes, you can do it via the methods you mentioned.

  • tearDown method is enabled after every single test inside the class
  • tearDownAfterClass method is enabled at the end of all tests inside the class

I would suggest you use a rollback pattern, so

  • in the setUp method you would initialize the transaction
    protected function setUp(): void
    {
        //...some boilerplate with establish connection
        $this->connection->beginTransaction();
    }
  • in tearDown method you would rolling back changes made in tests
    protected function tearDown(): void
    {
        $this->connection->rollback();
    }
like image 162
Kacper Majczak Avatar answered Jan 20 '26 01:01

Kacper Majczak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!