Symfony 3.4 PHPUnit testing database data

Hey guys, this post is a follow up from my last phpunit in Symfony2 post. This time I’ve had to install a test environment in a Symfony 3.4 project and I’ve had some weird problems, so I thought of writing this blog post once I solved them all, it may be helpful to someone out there :)

Step 1 — Installing a fresh Symfony 3.4 project.

In your symfony project, run the composer require

Now run the phpunit command to run tests.

Right off the bat, it’ll give you an error…

This problem is due to an incompatibility with code dependencies from PHPUnit and Symfony 3.2+ code, specifically with the Yaml component.

Don’t panic though, PHPUnit is working to solve this issue.

More info on the PHPUnit issue here.
More info on Symfony’s explanation here.

In the meantime, we can use the PHPUnit bridge to test our application.

Once your composer json and lock have updated, it’s time to run the test!

It works!!

Step 2 — Installing doctrine’s fixtures bundle.

First run the composer require

Once your composer json and lock have updated, it’s time to install it in our Kernel.

Now it’s installed, let’s create our first fixture. Let’s suposse we installed FOSUserBundle to manage our users, so for instance we could create a couple users like so:

Now if we run the fixtures like so

We’ll get another error:

To fix this, we’ll need to add this to services.yml

Yes, you guessed it, the magic here relies on the tag. Doctrine will load all services that have that ‘doctrine.fixture.orm’ tag. On the other hand, it’ll also load all the classes that implement the ORMFixtureInterface (for instance, those classes extending the Fixture class). More info on all of this in the DoctrineFixtureBundle doc page.

Step 3 — Setting a separate database for testing.

Add these lines on your config_test.yml file.

This will point to the new test database.

Then add the data in parameters.yml (don’t forget parameters.yml.dist for future installs)

Step 4 — Creating a TestCase that we will extend when ddbb fixtures are needed.

This is useful for reusing code, instead of writing it on every file. It also makes all the fixture tests more consistent.

This will create the database and install the fixtures on every test that extends this TestCase. This is important as you want a consistent database with the same data every time!

Step 5 — Creating the unit, functional and integration tests

After creating your test fixtures, now you can test your services logic easily by extending the TestCase we just created, like so.

Now you just need to run the phpunit command like so

I’ve created a bash wrapper script called ‘test’ that contains just this line of code so now I just need to run

Happy coding and testing! :)

Originally published at Joey’s blog.

Coder, Entrepreneur, Co-founder at SlowCode