Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Symfony2 unit tests more DRY by extending WebTestCase

A lot of my tests have a lot of the same setUp()/tearDown() stuff going on. It seems dumb to copy and paste the same code into every single one of my unit tests. I think I want to create a new test class that extends WebTestCase that my other tests can extend.

My problem is that I don't really know how. First of all, where's the most appropriate place to put this new class? I tried making one just inside my Tests folder, but then none of my tests could actually find the class. Maybe I just don't understand namespaces.

Has anyone extended WebTestCase before in the way I'm talking about? If so, how did you do it?

like image 765
Jason Swett Avatar asked Jun 07 '12 19:06

Jason Swett


2 Answers

I haven't done this, but I'd probably just do it like so

src/Your/Bundle/Test/WebTestCase.php

<?php

namespace Your\Bundle\Test

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as WTC;

class WebTestCase extends WTC
{
  // Your implementation of WebTestCase
}
like image 165
Peter Bailey Avatar answered Oct 12 '22 03:10

Peter Bailey


In my tests I usually extend the WebTestCase the way Peter proposed it. Additionally I use require_once to make the AppKernel available in my WebTestCase:

<?php

namespace My\Bundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;

require_once(__DIR__ . "/../../../../app/AppKernel.php");

class WebTestCase extends BaseWebTestCase
{
  protected $_application;

  protected $_container;

  public function setUp()
  {
    $kernel = new \AppKernel("test", true);
    $kernel->boot();
    $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    $this->_application->setAutoExit(false);

...

My tests then look like this:

<?php

namespace My\Bundle\Tests\Controller;

use My\Bundle\Tests\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
...
like image 41
Pierre Avatar answered Oct 12 '22 02:10

Pierre