As a PHP developer, you may use the Test-Driven Development (TDD) technique to develop your software by writing tests. Typically, TDD will divide each task of the development into individual units. A test is then written to ensure that the unit behaves as expected.
Every project that uses Test-Driven Development follows three simple steps repeatedly:
- Write a test for the next bit of functionality you want to add.
- Write the functional code until the test passes.
- Refactor both new and old code to make it well structured.
Continue cycling through these three steps, one test at a time, building up the functionality of the system. Testing will help you to refactor, which allows you to improve your design over time and makes some design problems more obvious.
The tests that contain small individual components are called unit tests. While unit tests can be carried out independently, if you test some of the components when they are integrated with other components, you are doing integration testing. The third kind of testing is test stubs. Test stubs allow you to test your code without having to make real calls to a database.
Why TDD Works
Nowadays, as you may use modern PHP IDE syntax, feedback is not a big deal. One of the important aspects of your development is making sure that the code does what you expect it to do. As software is complicated (different components integrated with each other), it would be difficult for all of our expectations to come true. Especially at the end of the project, due to your development, the project will become more complex, and thus more difficult to debug and test.
TDD verifies that the code does what you expect it to do. If something goes wrong, there are only a few lines of code to recheck. Mistakes are easy to find and fix. In TDD, the test focuses on the behavior, not the implementation. TDD provides proven code that has been tested, designed, and coded.
PHPUnit & Laravel
PHPUnit is the de-facto standard for unit testing PHP. It’s essentially a framework for writing tests and providing the tools that you will need to run tests and analyze the results. PHPUnit derives its structure and functionality from Kent Beck’s SUnit.
There are several different assertions that can help you test the results of all sorts of calls in your applications. Sometimes you have to be a bit more creative to test a more complex piece of functionality, but the assertions provided by PHPUnit cover the majority of cases you would want to test. Here is a list of some of the more common ones you will find yourself using in your tests:
- AssertTrue: Check the input to verify it equals true.
- AssertFalse: Check the input to verify it equals false value.
- AssertEquals: Check the result against another input for a match.
- AssertArrayHasKey(): Reports an error if array does not have the key.
- AssertGreaterThan: Check the result to see if it’s larger than a value.
- AssertContains: Check that the input contains a certain value.
- AssertType: Check that a variable is of a certain type.
- AssertNull: Check that a variable is null.
- AssertFileExists: Verify that a file exists.
- AssertRegExp: Check the input against a regular expression.
By default, PHPUnit 4.0 is installed in Laravel, and you may run the following command to update it:
composer global require "phpunit/phpunit=5.0.*"
The phpunit.xml
file in the Laravel root directory will let you do some configurations. In this case, if you want to override the default configuration you can edit the file:
<?xml version="1.0" encoding="UTF-8"?> <phpunit backupGlobals="false" backupStaticAttributes="false" bootstrap="bootstrap/autoload.php" colors="true" convertErrorsToExceptions="true" convertNoticesToExceptions="true" convertWarningsToExceptions="true" processIsolation="false" stopOnFailure="false" syntaxCheck="false"> <testsuites> <testsuite name="Application Test Suite"> <directory>./tests/</directory> </testsuite> </testsuites> <filter> <whitelist> <directory suffix=".php">app/</directory> </whitelist> </filter> <php> <env name="APP_ENV" value="testing"/> <env name="CACHE_DRIVER" value="array"/> <env name="SESSION_DRIVER" value="array"/> <env name="QUEUE_DRIVER" value="sync"/> <env name="DB_DEFAULT" value="sqlite_testing"/> <env name="DB_HOST" value="localhost"/> <env name="DB_DATABASE" value="laravel"/> <env name="DB_USERNAME" value="root"/> <env name="DB_PASSWORD" value="root"/> </php> </phpunit>
As you see in the code above, I have added the sample (not used in the article) database configuration.
What Is Doctrine ORM?
Doctrine is an ORM which implements the data mapper pattern and allows you to make a clean separation of the application’s business rules from the persistence layer of the database. To set up Doctrine, there is a bridge to allow for matching with Laravel 5’s existing configuration. To install Doctrine 2 within our Laravel project, we run the following command:
composer require laravel-doctrine/orm
As usual, the package should be added to the app/config.php
, as the service provider:
LaravelDoctrine\ORM\DoctrineServiceProvider::class,
The alias should also be configured:
'EntityManager' => LaravelDoctrine\ORM\Facades\EntityManager::class
Finally, we publish the package configuration with:
php artisan vendor:publish --tag="config"
How to Test Doctrine Repositories
Before anything else, you should know about fixtures. Fixtures are used to load a controlled set of data into a database, which we need for testing. Fortunately, Doctrine 2 has a library to help you write fixtures for the Doctrine ORM.
To install the fixtures bundle in our Laravel App, we need to run the following command:
composer require --dev doctrine/doctrine-fixtures-bundle
Let’s create our fixture in tests/Fixtures.php
:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class Fixtures implements FixtureInterface { /** * Load the Post fixtures * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $Post = new Post(['title'=>'hello world','body'=>'this is body']); $manager->persist($Post); $manager->flush(); } }
As you see, your fixture class should implement the FixtureInterface
and should have the load(ObjectManager $manager)
method. Doctrine2 fixtures are PHP classes where you can create objects and persist them to the database. To autoload our fixtures in Laravel, we need to modify composer.json
in our Laravel root:
... "autoload-dev": { "classmap": [ "tests/TestCase.php", "tests/Fixtures.php" //added here ] }, ...
Then run:
composer dump-autoload
Let’s create our test file in the tests directory DoctrineTest.php
.
namespace Test; use App; use App\Entity\Post; use Doctrine\Common\DataFixtures\Executor\ORMExecutor; use Doctrine\Common\DataFixtures\Purger\ORMPurger; use Doctrine\Common\DataFixtures\Loader; use App\Repository\PostRepo; class doctrineTest extends TestCase { private $em; private $repository; private $loader; public function setUp() { parent::setUp(); $this->em = App::make('Doctrine\ORM\EntityManagerInterface'); $this->repository = new PostRepo($this->em); $this->executor = new ORMExecutor($this->em, new ORMPurger); $this->loader = new Loader; $this->loader->addFixture(new Fixtures); } /** @test */ public function post() { $purger = new ORMPurger(); $executor = new ORMExecutor($this->em, $purger); $executor->execute($this->loader->getFixtures()); $user = $this->repository->PostOfTitle('hello world'); $this->em->clear(); $this->assertInstanceOf('App\Entity\Post', $user); } }
In the setUp()
method, I instantiate the ORMExecutor
and the Loader. We also load the Fixtures
class we just implemented.
Do not forget that the /** @test */
annotation is very important, and without this the phpunit will return a No tests found in class
error.
To begin testing in our project root, just run the command:
sudo phpunit
The result would be:
PHPUnit 4.6.6 by Sebastian Bergmann and contributors. Configuration read from /var/www/html/laravel/phpunit.xml. Time: 17.06 seconds, Memory: 16.00M OK (1 test, 1 assertion)
If you want to share objects between fixtures, it is possible to easily add a reference to that object by name and later reference it to form a relation. Here is an example:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class PostFixtures implements FixtureInterface { /** * Load the User fixtures * * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $postOne = new Post(['title'=>'hello','body'=>'this is body']); $postTwo = new Post(['title'=>'hello there ','body'=>'this is body two']); $manager->persist($postOne); $manager->persist($postTwo); $manager->flush(); // store reference to admin role for User relation to Role $this->addReference('new-post',$postOne); } }
and the Comment fixture:
namespace Test; use Doctrine\Common\Persistence\ObjectManager; use Doctrine\Common\DataFixtures\FixtureInterface; use app\Entity\Post; class CommentFixtures implements FixtureInterface { /** * Load the User fixtures * * @param ObjectManager $manager * @return void */ public function load(ObjectManager $manager) { $comment = new Comment(['title'=>'hello','email'=>'[email protected]','text'=>'nice post']); $comment->setPost($this->getReference('new-post')); // load the stored reference $manager->persist($comment); $manager->flush(); // store reference to new post for Comment relation to post $this->addReference('new-post',$postOne); } }
With two methods of getReference()
and setReference()
, you can share object(s) between fixtures.
If ordering of fixtures is important to you, you can easily order them with the getOrder
method in your fixtures as follows:
public function getOrder() { return 5; // number in which order to load fixtures }
Notice the ordering is relevant to the Loader class.
One of the important things about fixtures is their ability to resolve dependency problems. The only thing you need to add is a method in your fixture as I did below:
public function getDependencies() { return array('Test\CommentFixtures'); // fixture classes fixture is dependent on }
Conclusion
This is just a description of Test-Driven Development with Laravel 5 and PHPUnit. When testing repositories, it’s inevitable that you are going to hit the database. In this case, Doctrine fixtures are important.
Comments