Sending a POST request using PHPUnit

I have a symfony site and am trying to run some unit tests. I have a test where I'm trying to imagine something:

<?php namespace Acme\AcmeBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class HomeControllerTest extends WebTestCase { public function testrandomeThings() { $client = static::createClient(); $crawler = $client->request( 'POST', '/', array( "shopNumber" => 0099, "cardNumber" => 231, "cardPIN" => "adasd"), array(), array()); } 

but I don’t think Im sending data to the controller:

 class HomeController extends Controller { public function indexAction() { var_dump($_POST); die; return $this->render('AcmeBundle:Home:index.html.twig'); } } 

the var_dump actually returns me an empty array.

What am I missing to send information through my POST request?

+5
post php tdd symfony phpunit
source share
2 answers

$_POST is a variable populated by PHP, and a symfony request is created only from these global characters if called directly via http. The symfony crawler does not make a real request, it creates a request from the parameters provided in your $client->request , and executes it. You need to access this material using the Request object. Never use $_POST , $_GET , etc. Directly.

 use Symfony\Component\HttpFoundation\Request; class HomeController extends CoralBaseController { public function indexAction(Request $request) { var_dump($request->request->all()); die; return $this->render('CoralWalletBundle:Home:index.html.twig'); } } 

use $request->request->all() to get all the POST parameters in the array. To get only a specific parameter, you can use $request->request->get('my_param') . If you ever need access to GET parameters, you can use $request->query->get('my_param') , but it is better to set the request parameters already in the routing template.

+7
source share

I think you are trying to do this:

 $client = static::createClient(); $client->request($method, $url, [], [], [], json_encode($content)); $this->assertEquals( 200, $client->getResponse() ->getStatusCode() ); 

You put your data (content) as an array of params, but you want to place it as the raw content of the body, which is JSON encoding.

+2
source share

All Articles