Sending a POST request with PHPUnit

China☆狼群 提交于 2020-01-22 15:20:12

问题


I have a symfony website, and Im trying to do some unit testing. I have this kind of test where I try to submit 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 dont think that the data Im sending is being received in the controler:

class HomeController extends Controller
{
    public function indexAction()
    {

        var_dump($_POST);
        die;
        return $this->render('AcmeBundle:Home:index.html.twig');
    }

}

the var_dump is actually returning me an empty array.

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


回答1:


$_POST is a variable filled by PHP and the symfony request is only created from this globals if called directly over http. The symfony crawler doesn't make a real request, it creates a request from the parameters supplied in your $client->request and executes it. You need to access this stuff via 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 POST parameters in an array. To get only a specific parameter you can use $request->request->get('my_param'). If you ever need to acces GET parameters you can use $request->query->get('my_param'), but better set query parameters already in the routing pattern.




回答2:


I think you're trying to do this:

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

You're putting your data (content) in as the params array but you want to put it in as the raw body content which is a JSON encoded string.



来源:https://stackoverflow.com/questions/18900890/sending-a-post-request-with-phpunit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!