使用PHPUnit发送POST请求 [英] Sending a POST request with PHPUnit

查看:466
本文介绍了使用PHPUnit发送POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个symfony网站,我正在尝试进行一些单元测试.我在尝试提交某些东西的地方进行了这种测试:

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');
    }

}

var_dump实际上返回了一个空数组.

the var_dump is actually returning me an empty array.

通过POST请求发送信息时我缺少什么?

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

推荐答案

$_POST是PHP填充的变量,仅当直接通过http调用时,symfony请求才从此全局变量创建. symfony搜寻器不会发出真正的请求,它会根据您的$client->request中提供的参数创建一个请求并执行该请求.您需要通过 Request 对象访问这些内容.切勿直接使用$_POST$_GET等.

$_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');
    }

}

使用$request->request->all()获取数组中的所有POST参数.要仅获取特定参数,可以使用$request->request->get('my_param').如果需要访问GET参数,可以使用$request->query->get('my_param'),但最好在路由模式中设置查询参数.

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.

这篇关于使用PHPUnit发送POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆