Answer the question
In order to leave comments, you need to log in
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();
$crawler = self::$client->request('GET', $uri);
Answer the question
In order to leave comments, you need to log in
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;
}
}
<?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();
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question