简体   繁体   中英

PHPUnit POST request not sending parameters with Symfony2

I am writing a Symfony2 PHPUnit functional test to test a form page. In the test I am attempting to create a POST request containing form parameters, send them to a createAction, and assert that the page rerouted. The problem is that my controller is not receiving the request parameters. My test is:

$client = static::createClient();
$client->followRedirects();

$client->request('POST', '/create/adviseeSet', array(
        'name' => 'Monkey Hour',
        'advisor' => '523',
        'day' => 'Monday',
        'year' => '20'
    ),
    array()
);

$this->assertTrue($client->getResponse()->isRedirect());

The controller action begins as follows:

public function createAction(Request $request) {
    $params = $request->request->all();
    var_dump($params);
    // create entity and reroute user
}

The var_dump output is an empty array. However if I change my request method to a GET,

$client->request('GET', '/create/adviseeSet', array(
        'name' => 'Monkey Hour',
        'advisor' => '523',
        'day' => 'Monday',
        'year' => '20'
    ),
    array()
);

And var_dump the request's query

$params = $request->query->all();

I see my parameters!

   array(4) {
     ["advisor"]=>
   string(3) "523"
     ["day"]=>
   string(6) "Monday"
     ["name"]=>
   string(11) "Monkey Hour"
     ["year"]=>
   string(2) "20"
   }

How can I get my POST Request to perform as well at the GET request?

If you are writing functional tests you should always check html output like this var_dump($client->getResponse()->getContent()) ; .
Maybe you have forgotten to add csrf token. Here is example:

$csrfToken = $client->getContainer()->get('form.csrf_provider')
     ->generateCsrfToken('form_intention');

$client->request('POST', '/create/adviseeSet', array(
    'name' => 'Monkey Hour',
    'advisor' => '523',
    'day' => 'Monday',
    'year' => '20',
    '_token' => $csrfToken
    )
);

$crawler = $client->followRedirect();

$this->assertTrue(...);

Don't forget to add intention in your form type:

$resolver->setDefaults(array(
            //some params 
            'intention' => 'form_intention',
        ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM