Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 tdd developing

Can anyone please provide a standard example for developing in Symfony2 using the TDD notation? Or share links to interesting materials for TDD Symfony2 development (except the official documentation :))?

P.S. Is anybody writing unit tests for controller part of MVC pattern?

like image 548
Aleksei Kornushkin Avatar asked May 09 '11 02:05

Aleksei Kornushkin


1 Answers

I just did it for silex, which is a micro-framework based on Symfony2. From what I understand, it's very similar. I'd recommend it for a primer to the Symfony2-world.

I also used TDD to create this application, so what I did was:

  1. I wrote my first test to verify the route/action
  2. Then I implemented the route in my bootstrap
  3. Then I added assertions to my test e.g., what should be displayed
  4. I implemented that in my code and so on

An example testcase (in tests/ExampleTestCase.php) looks like this:

<?php
use Silex\WebTestCase;
use Symfony\Component\HttpFoundation\SessionStorage\ArraySessionStorage;

class ExampleTestCase extends WebTestCase
{
    /**
     * Necessary to make our application testable.
     *
     * @return Silex\Application
     */
    public function createApplication()
    {
        return require __DIR__ . '/../bootstrap.php';
    }

    /**
     * Override NativeSessionStorage
     *
     * @return void
     */
    public function setUp()
    {
        parent::setUp();
        $this->app['session.storage'] = $this->app->share(function () {
            return new ArraySessionStorage();
        });
    }

    /**
     * Test / (home)
     *
     * @return void
     */
    public function testHome()
    {
        $client  = $this->createClient();
        $crawler = $client->request('GET', '/');

        $this->assertTrue($client->getResponse()->isOk());
    }
}

my bootstrap.php:

<?php
require_once __DIR__ . '/vendor/silex.phar';

$app = new Silex\Application();

// load session extensions
$app->register(new Silex\Extension\SessionExtension());

$app->get('/home', function() use ($app) {
    return "Hello World";
});
return $app;

My web/index.php:

<?php
$app = require './../bootstrap.php';
$app->run();
like image 198
Till Avatar answered Sep 22 '22 16:09

Till