Posts Tagged ‘plugins’

Plugins unit testing

About unit testing

From the Symfony book :

Unit tests confirm that a unitary code component provides the correct output for a given input. They validate how functions and methods work in every particular case. Unit tests deal with one case at a time, so for instance a single method may need several unit tests if it works differently in certain situations.

If you write a Symfony plugin that deals with models, say a behavior, you are also invited to write a functional test to make sure that your objects behave correctly.

In that test, you must be able to instantiate one or many objects in a real application context, call methods, save, and check that the final state matches your requirements.

Unit test your plugin

Just like an application unit test, let’s create this file structure:

~plugins/
 `~sfPropelActAsSomethingBehaviorPlugin/
   |+config/
   |+lib/
   |~test/
   | |~bootstrap/
   | | |-fixtures.yml
   | | `-functional.php
   | `~unit/
   |   `-somethingTest.php

Put some sample data in fixtures.yml. Ex:

Article:
  article_1:
    title: my first article
    body: blablabla
    author_id: 1
Author:
  author_1:
    name: nicolas

bootstrap.php will do the following stuff:

  • Set up the test database connection
  • Delete existing data
  • Load fresh new fixtures
$app = ’frontend‘;
require_once dirname(__FILE__)./../../../../config/ProjectConfiguration.class.php‘;
$configuration = ProjectConfiguration::getApplicationConfiguration($app, ‘test‘, isset($debug) ? $debug : true);
sfContext::createInstance($configuration);

$fixtures = dirname(__FILE__)./fixtures.yml‘;
$databaseManager = new sfDatabaseManager($configuration);
$databaseManager->initialize($configuration);
$con = Propel::getConnection();

ArticlePeer::doDeleteAll();
AuthorPeer::doDeleteAll();

$data = new sfPropelData();
$data->loadData($fixtures, ‘propel‘);

Now, let’s write the test in somethingBehaviorTest.php, using the freshly initialized database with fixtures loaded :

include(dirname(__FILE__)./../bootstrap/functional.php‘);
include($configuration->getSymfonyLibDir()./vendor/lime/lime.php‘);

$t = new lime_test(23, new lime_output_color());

$c = new Criteria;
$c->add(Author::NAME, ‘nicolas‘);
$author = AuthorPeer::doSelectOne($c);

$t->is($author->countStuff(), 3, "author_1 should have \"3\" stuff");
…

Test !

$ php plugins/sfActAsSomethingPlugin/test/unit/somethingTest.php
1..23
ok 1 - Author_1 should have 3 stuff

Note

foreign references must be respected when deleting data. Then, you must detete them in the correct order (ex: Articles before Authors).

Fixtures must be declared in the correct order as well (ex: Authors before Articles) as they will be inserted sequentially.