Run Symfony2 unit tests over DRY by extending WebTestCase

Many of my tests contain a lot of the same things setUp()/ tearDown(). It seems silly to copy and paste the same code into each of my unit tests. I think I want to create a new test class that extends WebTestCaseso that my other tests can expand.

My problem is that I really don't know how to do this. First of all, where is the best place to place this new class? I tried to do this only inside my folder Tests, but then none of my tests could find the class. Maybe I just don't understand the namespace.

Has anyone expanded WebTestCasebefore I speak? If so, how did you do this?

+5
source share
4 answers

I did not do this, but I would just do it like that

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
}
+4
source

In my tests, I usually extend WebTestCase as Peter suggested. In addition, I use require_once to make 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 look like this:

<?php

namespace My\Bundle\Tests\Controller;

use My\Bundle\Tests\WebTestCase;

class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
...
+2
source

WebTestCase AppKernel.

    $client = static::createClient();
    self::$application = new Application($client->getKernel());
+2

, Google, .

WebTestCase setUp logIn, .

, tests, . , . , src/_TestHelpers .

So, I have a:

# src/_TestHelpers/ExtendedWTC.php
namespace _TestHelpers;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class ExtendedWTC extends WebTestCase
{
    # Do your cool extending here
}

and

# tests/AppBundle/Controller/DefaultControllerTest.php
namespace Tests\AppBundle;

use _TestHelpers\ExtendedWTC

class DefaultControllerTest extends ExtendedWTC
{
    # Your tests here, using your cool extensions.
}

Note. I use a directory structure Symfony 3, so my tests are in tests/, not src/AppBundle/Tests/.

I hope this helps someone ...

0
source

All Articles