Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with PHPUnit and a semi-persistent database

Tags:

php

phpunit

I'm new to unit testing and I'm trying to get started with PHPUnit on an existing project I'm working on.

The problem I'm facing is that I have lots of unit tests that require a database which is fair enough. I've set up an SQLite DB for the sole purpose of unit testing. Sometimes I want to drop and re-create the database for new tests (by this I mean each separate classes), to prevent unnecessary data clashes.

However, sometimes I don't want this to happen if I have unit tests in the same class that depend upon one another; these may need access to data that was saved in a previous test.

I am currently getting a "fresh" database in the setUp() function of each class. What I didn't anticipate is that this function (as with __construct()) would run after every test case within said class.

Is there a way that I can flush the database with each test class? Or am I going about the entire process incorrectly?

Any tips appreciated, thanks.

like image 235
James Avatar asked May 10 '26 19:05

James


1 Answers

I also started using PHPUnit fairly recently (about a year ago). The first thing I did was to set up unit tests for the project I was working on at the time. I decided it was a good idea to test the data access layer too and did a similar thing to you. It took me days to set up and I ended up with unit tests that took 8 minutes to run! 99% of that time was spent setting up and tearing down the test database. What a disaster!

What I did was to refactor the project so that only one class actually needed to talk to the database and had integration tests for this, but no unit tests. That meant that my project now had to use dependency injection to facilitate testing. I ended up with a suite of tests that run in around 2-3 seconds and a project that practically wrote itself. It is a dream to maintain and make changes/additions to, I wish all my code had been written that way.

Basically, what I am trying to say in my long winded way is that you should change your code to be easy to test, not try and force the unit tests to fit code not designed in a test driven way. The time you invest in that now (if you can) will be repaid back later with dividends!

Bite the bullet and refactor now!

like image 121
vascowhite Avatar answered May 13 '26 09:05

vascowhite



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!