FLASH SALE! Up to 40% off on unlimited courses, tutorials and creative asset downloads SAVE NOW
  1. Code
  2. TDD

Test-Driven Development With Laravel & Doctrine


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:

bash 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:


./tests/ app/


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:

bash composer require laravel-doctrine/orm

As usual, the package should be added to the app/config.php, as the service provider:

php LaravelDoctrine\ORM\DoctrineServiceProvider::class,

The alias should also be configured:

php 'EntityManager' => LaravelDoctrine\ORM\Facades\EntityManager::class

Finally, we publish the package configuration with:

bash 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:

bash composer require --dev doctrine/doctrine-fixtures-bundle

Let’s create our fixture in tests/Fixtures.php:

```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:

json ... "autoload-dev": { "classmap": [ "tests/TestCase.php", "tests/Fixtures.php" //added here ] }, ...

Then run:

bash composer dump-autoload

Let’s create our test file in the tests directory DoctrineTest.php.

```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); }

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:

bash sudo phpunit

The result would be:

```bash 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:

```php 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();

and the Comment fixture:

```php 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’=>’alirezarahmani@live.com’,’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:

php 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:

php public function getDependencies() { return array('Test\CommentFixtures'); // fixture classes fixture is dependent on }


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.

Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.