A
A
Alexey Dabalaev2020-11-07 22:05:58
symfony
Alexey Dabalaev, 2020-11-07 22:05:58

How to test a controller method in Symfony5?

Hello.
Maybe someone faced such a problem (or maybe not a problem at all): the controller action ends up like this:

echo file_get_contents($path);
exit();


those. the echo function returns an image.

I'm trying to test this in this way: As a result, a lot of characters are poured into the console (the image itself is given by the action via echo). Is it even possible to test this? If so, how?

$crawler = self::$client->request('GET', $uri);


Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Daria Motorina, 2020-11-08
@glaphire

I haven’t encountered this before, but there is a moment in the description of the question - just echo the content and exit will not work, to output the file, you also need to add content headers, file size and output method. Those. in such a form as the controller method is now, I don’t understand how it can work correctly)
Even if without modifications, it is enough to use ob_start () and ob_get_clean () to prevent the output of the file content to the console.
Improved example:
Controller:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\Routing\Annotation\Route;

class TestController extends AbstractController
{
    /**
     * @Route("/get-image", name="get_image")
     */
    public function getImage()
    {
        $path = "/home/dariia/Code/sf5_http_kernel_course/public/uploads/article_image/lightspeed-5f687f2402b6f.png";

        $response = new BinaryFileResponse($path);

        return $response;
    }
}

Test:
<?php

namespace App\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class TestControllerTest extends WebTestCase
{
    public function testRegister()
    {
        $client = static::createClient();
        ob_start();
        $client->request('GET', '/get-image');
        $client->getResponse()->sendContent();
        $this->assertResponseIsSuccessful();
        $this->assertResponseHeaderSame('Content-Type', 'image/png');
        ob_get_clean();
...

Then you can add assertions on the topic of file size, name, etc., you just need to have some kind of binding to the file in order to manipulate this data, and I simplified the example)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question