How to use PHPUnit fixtures in your Yii2 development

Submitted by Peter Majmesku on Mon, 08/29/2016 - 19:04

Often you need to create extra database data to run your PHPUnit test, when you're creating your application with Yii2 framework. The best is, that you're doing this work only once and save this with your test, so that you can re-use this test data on every test run. This data is called "fixtures". I want to introduce you my approach of using fixtures with CSV files, which are containing the data which will be written into your database, as you're fireing your PHPUnit test. For programming and running PHPUnit tests I prefer PhpStorm. But you can test your code also with PHPUnit by command line of some configuration in Netbeans or Eclipse with PHP configuration.

PhpMyAdmin and MySQL workbench are allowing you to export CSV files with your database data and the column-names in the first line of the export. The contents of the first line are the names of your properties, which are defined in your Yii model. Ok, let's say you have such exports, you need to have your PHPUnit test.

use app\tests\fixtures\ModelFixtureDataCreator;
MyTest extends PHPUnit_Framework_TestCase
    protected function 
$test_classname get_class($this);
    public function 

At the beginning you see, that I use the ModelFixtureDataCreator(); class for creating my fixtures for the PHPUnit test. The folder structure in my project is the same as in the namespace. I'll explain you the ModelFixtureDataCreator(); class later in detail. The first method in my test is setUp(); which works like a constructor in PHPUnit. I require a file which is booting Yii2 for me, so that I can use it in my unit tests.

if(is_numeric(strpos(getcwd(), '/tests'))){
getcwd() . '/../';
} else {
getcwd() . '/';

This code is very easy, it handles just the paths for me, so that I don't have to mind from which folder I start my tests. This file is just booting Yii's console application. It's just the file you use to run your Gii application from the command line.

I've modified it a bit for my needs (you're free to modify yours as you wish):

<?php defined('YII_DEBUG') or define('YII_DEBUG'true);
// fcgi doesn't have STDIN and STDOUT defined by default
defined('STDIN') or define('STDIN'fopen('php://stdin''r'));
defined('STDOUT') or define('STDOUT'fopen('php://stdout''w'));
__DIR__ '/vendor/autoload.php');
__DIR__ '/vendor/yiisoft/yii2/Yii.php');
defined('ENVIRONMENT') or define('ENVIRONMENT''dev');
$argv false;
// the path to your config file.
$config = require_once('the/path/to/your/config/file.php');

Then I determine the name of my test class and pass it finally to my ModelFixtureDataCreator(); class, where I call the create-method statically:

<?php $test_classname get_class($this);

The magic from the ModelFixtureDataCreator(); class is, that it uses "convention over configuration". Once you have the following folder structure the class is able to create all fixture data in relation to your test.

- your yii2 application folder
-- tests folder
--- fixtures folder
---- folder exactly named like your test without the file extension (f.e. ExportControllerTest)
----- the csv files exactly named like your models (f.e. MyModel.csv)

 Downwards you can see the code from ModelFixtureDataCreator(); class with it's comments.

<?php amespace app\tests\fixtures;


 * Class ModelFixtureDataCreator
 * @package app\tests\fixtures
class ModelFixtureDataCreator {

     * Reads the CSV files from the test related fixture folder, instantiates
     * the model by the CSV filename without the file-extension and passes
     * it to the writeFixtureDataForModelIntoDb(); method with the modelname
     * and the test classname.
     * @param $test_classname
public static function create($test_classname){
$path__fixture_folder 'fixtures/' $test_classname;

$handle__fixture_folder opendir($path__fixture_folder);

        while ((
$file readdir($handle__fixture_folder)) !== false){
is_file($path__fixture_folder '/' $file)){

$arr__pathinfo pathinfo($file);
$str__modelname str_replace('.' $arr__pathinfo['extension'],

$str__modelpath 'app\\models\\' $str__modelname;

$obj__model_instance = new $str__modelpath;



     * Uses the first line from the CSV file as the model properties. Then
     * the method treats the next lines as values and writes them to the model
     * related database table.
     * @param $obj__model_instance
     * @param $str__modelname
     * @param $test_classname
private static function writeFixtureDataForModelIntoDb($obj__model_instance,

$fp fopen("fixtures/$test_classname/$str__modelname'.csv''r');

$first_row_runed false;
$properties = array();
        while ((
$data fgetcsv($fp1000",")) !== FALSE) {
$first_row_runed === false){
$properties $data;
            } else {
$sub_counter 0;
$data as $d){
$obj__model_instance->$properties[$sub_counter] = $d;

$first_row_runed true;


The class is currently only writing fixture data into your database. By the tearDown(); method from your PHPUnit test you're able to implement logic, which is deleting the fixture data after your test has been runned.

Do you have any ideas for this approach? Share them!

Subscribe to PHPUnit