Trent
Trent

Reputation: 5877

How to test response headers in Symfony2?

I wrote a response listener to bypass some specific content-type and I'm wondering what is the best way to UnitTest it.

Do you have any clue on how I could do that?

Do I need to create Controller fixture to test against?

Do functionnal tests are allowed inside an unit test suite?

Upvotes: 3

Views: 3082

Answers (3)

You can use this.

            $logger = $this->client->getContainer()->get('logger');
            $logger->info("data->" . $response->headers->get("Location"));

Upvotes: 1

kratos
kratos

Reputation: 2495

From the docs, here is a Unit test:

// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace Acme\DemoBundle\Tests\Utility;

use Acme\DemoBundle\Utility\Calculator;

    class CalculatorTest extends \PHPUnit_Framework_TestCase
    {
        public function testAdd()
        {
            $calc = new Calculator();
            $result = $calc->add(30, 12);

            // assert that your calculator added the numbers correctly!
            $this->assertEquals(42, $result);
        }
    }

Here is a functional test:

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();

        $crawler = $client->request('GET', '/demo/hello/Fabien');

        $this->assertGreaterThan(
            0,
            $crawler->filter('html:contains("Hello Fabien")')->count()
        );
    }
}

Please keep in mind that the functional test cannot test Ajax etc so a heavy Ajax site will best be tested using a functional browser testing framework.

Good luck

Upvotes: 1

Jakub Zalas
Jakub Zalas

Reputation: 36191

Writing unit test for listeners is fairly simple. You just need to mock the objects your listener depends on. Look for example tests in Symfony source code.

Another way might be writing a functional test.

Upvotes: 1

Related Questions