Search code examples
symfonytestingintegration-testingweb-testing

Is Symfony WebTestCase only internal?


Is Symfony WebTestCase a tool that just boots the Kernel and tests the Response object or it spawns a PHP Web Server and makes the test against the server?

This is to know if I can test a legacy app that lives outside Symfony Framework


Solution

  • As you can see, from source code, the client that make requests is defined as a a service called 'test.client'.

    namespace Symfony\Bundle\FrameworkBundle\Test;
    use Symfony\Bundle\FrameworkBundle\Client;
    abstract class WebTestCase extends KernelTestCase
    {
        protected static function createClient(array $options = array(), array $server = array())
        {
            static::bootKernel($options);
            $client = static::$kernel->getContainer()->get('test.client');
            $client->setServerParameters($server);
            return $client;
        }
    }
    

    And the service is defined as

    <service id="test.client" class="Symfony\Bundle\FrameworkBundle\Client" shared="false">
        <argument type="service" id="kernel" />
        <argument>%test.client.parameters%</argument>
        <argument type="service" id="test.client.history" />
        <argument type="service" id="test.client.cookiejar" />     
    </service>
    

    The Symfony\Component\BrowserKit\Client::doRquest() is the one who make the request. Is an abstract method implemented in Symfony\Component\HttpKernel\Client::doRequest():

    protected function doRequest($request)
    {
        $response = $this->kernel->handle($request);
        if ($this->kernel instanceof TerminableInterface) {
            $this->kernel->terminate($request, $response);
        }
        return $response;
    } 
    

    This means that a request must be handled by the kernel. ... Going deep to the code You can see that a request must match with the matcher service. This means that you cannot request resources outside symfony.

    If you dont know how to test legacy code, ... you can use Guzzle client.

    public function test200()
    {
        $client = new GuzzleHttp\Client();
    
        $res = $client->request('GET', 'https://www.example.com');
    
        $this->assertEquals(
            200,
           $res->getStatusCode()
        );
    }