Php Symfony2验收测试不工作
目前,我正在为Symfony2应用程序编写验收测试用例。我在做以下事情Php Symfony2验收测试不工作,php,unit-testing,symfony,phpunit,symfony-routing,Php,Unit Testing,Symfony,Phpunit,Symfony Routing,目前,我正在为Symfony2应用程序编写验收测试用例。我在做以下事情 namespace my\Bundle\ProjectBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = s
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)"} []
似乎$\u服务器
变量中缺少一些值。是否有任何线索或更好的方法来编写测试用例
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);
}
不管怎样,我找到了一个或多或少的解决办法。如下图所示,这是一个测试用例
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());
}
}
我也试着跟着
但正确的解决方案仍有待讨论 您的解决方案正在发挥作用,但更好的方法可能是: 阅读: 有关request()方法的详细信息: request()方法的完整签名为:
request(
$method,
$uri,
array $parameters = array(),
array $files = array(),
array $server = array(),
$content = null,
$changeHistory = true
)
服务器阵列是您通常希望找到的原始值
在PHP$\u服务器中
超全局
因此,更为清洁的方法可能是:
$client->request(
'GET',
'/',
array(),
array(),
array(
'SERVER_PROTOCOL' => 'http://',
)
);
一个问题可能是您在SERVER\u协议
变量中设置的值。关于:
“服务器协议”信息协议的名称和版本,通过
这一页是被要求的;i、 e.“HTTP/1.0”
似乎真正的值是'HTTP/1.0'
(而不是HTTP://
)。因此,请仔细检查生成错误的类DataHelper.php
编辑:
您可以从symfony2请求访问HTTP_服务器变量(在中)
您还可以调用请求的方法:和,以获取此信息(例如,检查请求类的源代码)。在您的例子中,可能需要getScheme方法。例如:
$protocol = $req->getScheme();
希望这有帮助为什么要将https=>true作为参数传递?@COil这真的很重要吗?有问题吗?你能显示DataHelper.php类的代码吗?@Matteo谢谢。或者你可以修改DataHelper.php类来测试协议密钥是否存在。或者可以完全重新实现它以完全不依赖超全局变量。在获取服务器\ U协议时,为什么不使用请求堆栈服务呢?非常感谢您的评论。在Coil,我可以修改一个或两个类,以防在任何地方使用它,并且很难修改每个地方。其次,这是一个测试场景,但在prod或dev模式下,全局参数始终存在。在虫族重新实施只是为了测试也不是很好的解决方案。谢谢你的回答。
$protocol = $req->getScheme();