【问题标题】:Symfony: changing the request base class and updating the test environmentSymfony:更改请求基类并更新测试环境
【发布时间】:2015-06-16 15:34:01
【问题描述】:

我已按照accepted answer of this question 中的说明修改了我的应用程序的基本请求类。它工作得很好,除了在启动我的功能测试时,我收到以下错误:

控制器"My\Bundle\AppBundle\Controller\MyController::searchAction()" 要求您为“$request”参数提供一个值(因为没有默认值或因为在此参数之后有一个非可选参数)。 (500 内部服务器错误)

确实没有使用app_test.php 控制器。我希望它可以在我的WebTestCase 基类的createCient() 函数中完成,但是如何实现呢?

/**
 * Creates a Client.
 *
 * @param array $options An array of options to pass to the createKernel class
 * @param array $server  An array of server parameters
 *
 * @return Client A Client instance
 */
protected static function createClient(array $options = array(), array $server = array())
{
    static::bootKernel($options);

    $client = static::$kernel->getContainer()->get('test.client');
    $client->setServerParameters($server);

    return $client;
} 
  • 使用 Symfony 2.6.9。

[2017 年 9 月 21 日编辑]:

迁移到 Symfony 3.3 时我必须执行以下操作:

config_test.yml:

parameters:
    test.client.class: My\Bundle\AppBundle\Tests\Client

services:
    test.client:
        class: '%test.client.class%'
        arguments: ['@kernel', '%test.client.parameters%', '@test.client.history', '@test.client.cookiejar']

【问题讨论】:

标签: php symfony request phpunit


【解决方案1】:

我认为您必须覆盖 test.client 的类,默认情况下使用 Symfony\Bundle\FrameworkBundle\Client

类似:

<parameters>
    <parameter name="test.client.class">My\Bundle\AppBundle\Test\Client</parameter>
</parameters>

首先,看一下基类Symfony\Component\BrowserKit\Client

如果你查看这个类的request 方法,你会发现:

public function request(/* ... */)
{
    // ...
    $this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);

    $this->request = $this->filterRequest($this->internalRequest);
    // ...
}

现在看看Symfony\Component\HttpKernel\ClientfilterRequest 方法:

protected function filterRequest(DomRequest $request)
{
     $httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent());

    // ...
}

这就是真正的魔法发生的地方。如果您需要不同的请求对象,这是您必须重写的方法。

编辑:

然后这个$httpRequest 将被序列化和反序列化。看看Symfony\Component\HttpKernel\Client类的getScript方法就知道了。

【讨论】:

  • 感谢@awons 的提示!我将修改我的问题以添加有关我所做的事情的详细信息。现在一切都按预期工作,我的控制器中不再有“捷径”功能。
  • 对我来说,用 test.client.class 添加这些配置行有点令人困惑 - 它的配置文件 services.xxx(在我的例子中是 services.yml)。它的 parameters 属性就在文件的开头。
猜你喜欢
  • 2011-03-05
  • 1970-01-01
  • 2015-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
相关资源
最近更新 更多