Symfony2验收测试不起作用


Symfony2 acceptance test not working

目前,我正在为Symfony2应用程序编写验收测试用例。我正在做以下事情。

namespace my'Bundle'ProjectBundle'Tests'Controller;
use Symfony'Bundle'FrameworkBundle'Test'WebTestCase;
class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $client = static::createClient();
        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}

但它在查看以下日志文件时失败了。

app/logs/test.log

看来

[2016-09-06 12:56:58] request.CRITICAL: Uncaught PHP Exception PHPUnit_Framework_Error_Notice: "Undefined index: SERVER_PROTOCOL" at /var/www/src/my/Bundle/projectBundle/Helper/DataHelper.php line 139 {"exception":"[object] (PHPUnit_Framework_Error_Notice(code: 8): Undefined index: SERVER_PROTOCOL at /var/www/src/my/Bundle/projectBundle/Helper/DataHelper.php:139)"} []

$_SERVER变量中似乎缺少一些值。有任何线索或有更好的方法来编写测试用例吗。

DataHelper.php

public function getCanonicalUrl()
    {
        $router = $this->container->get('router');
        $req = $this->container->get('request');
        $route = $req->get('_route');
        if (!$route) {
            return 'n/a';
        }
        $url = $router->generate($route, $req->get('_route_params'));
        $protocol = stripos($_SERVER['SERVER_PROTOCOL'], 'https') === true ? 'https://' : 'http://';
        return $protocol . ($this->getHostname() . $url);
    }

您的解决方案正在运行,但更好的方法可能是:

阅读关于symfony2测试的文档:

关于request的更多信息((方法:

request((方法的完整签名是:

request(
    $method,
    $uri,
    array $parameters = array(),
    array $files = array(),
    array $server = array(),
    $content = null,
    $changeHistory = true
)

服务器数组是您通常期望找到的原始值在PHP $_SERVER超全局中。

因此,一种更清洁的方法可能是:

$client->request(
    'GET',
    '/',
    array(),
    array(),
    array(
        'SERVER_PROTOCOL'          => 'http://',
    )
);

一个问题可能与您在SERVER_PROTOCOL变量中设置的值有关。关于单据:

"SERVER_PROTOCOL"通过该页面是被请求的;即"HTTP/1.0";

实际值似乎是'HTTP/1.0'(而不是http://(。因此,请仔细检查生成错误的类DataHelper.php

编辑:

您可以从symfony2请求(在文档中(访问HTTP_SERVER变量

// retrieve $_SERVER variables
$request->server->get('HTTP_SERVER');

您也可以调用请求的方法:getScheme和isSecure来获取这些信息(例如,查看request类的源代码(。在您的情况下,可能需要getScheme方法。例如:

$protocol = $req->getScheme();

希望这能帮助

无论如何,到目前为止,我或多或少找到了一个解决方法。如下图所示,这是一个测试用例。

namespace Chip'Bundle'PraxistippsBundle'Tests'Controller;
use Symfony'Bundle'FrameworkBundle'Test'WebTestCase;
class DefaultControllerTest extends WebTestCase
{
    public function testIndex()
    {
        $_SERVER['SERVER_PROTOCOL'] = 'http://';
        $client = static::createClient();
        $client->request('GET', '/');
        $this->assertEquals(200, $client->getResponse()->getStatusCode());
    }
}

我也试着跟随。

堆栈溢出多一个答案

但一个正确的解决方案还有待讨论。