Symfony:更改请求基类并更新测试环境

时间:2015-06-16 15:34:01

标签: php symfony request phpunit

我修改了我的应用程序的基本Request类,如accepted answer of this question中所述。它运行得很好,除了启动我的功能测试时,我收到以下错误:

  

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

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

/**
 * 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']

1 个答案:

答案 0 :(得分:3)

我认为您必须覆盖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序列化并反序列化。只需查看getScript类的Symfony\Component\HttpKernel\Client方法。