gpt4 book ai didi

Symfony 单元测试和容器

转载 作者:行者123 更新时间:2023-12-02 16:30:00 25 4
gpt4 key购买 nike

在 Symfony 2 中进行单元测试时,我正在测试的 Controller 未接收到服务容器,导致测试失败,并出现旧的调用非对象上的成员函数 get()

我无法从测试 Controller 使用 $this->forward,因为它也没有服务容器。

我找到了这个引用资料,但似乎我会出于错误的原因使用它,有人有这方面的经验吗?

http://symfony.com/doc/current/book/testing.html#accessing-the-container

编辑:这是我的测试:

<?php

namespace HvH\ClientsBundle\Tests\Controller;

use HvH\ClientsBundle\Controller\ClientsController;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\HeaderBag;
use Symfony\Component\HttpFoundation\Session;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ClientsControllerTest extends WebTestCase
{

public function testGetClientsAction()
{

$client = static::createClient();
$container = $client->getContainer();
$session = $container->get('session');
$session->set('key', 'value');
$session->save();

$request = new Request;
$request->create('/clients/123456', 'GET', array(), array(), array(), array(), '');

$headers['X-Requested-With'] = "XMLHttpRequest";
$request->headers->add($headers);

/* This doesn't work */
/*
$controller = new Controller;
$status = $controller->forward( 'HvHClientsBundle:Clients:getClients', array('request' => $request) );
*/

$clients_controller = new ClientsController();
$status = $clients_controller->getClientsAction($request);

$this->assertEquals(200, $status);
}

}

这是客户端 Controller 失败的部分

<?php

namespace HvH\ClientsBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use HvH\APIschemaBundle\Controller\Validation;


//FOSRestBundle
use FOS\RestBundle\View\View;

class ClientsController extends Controller
{

//Query all clients
public function getClientsAction(Request $request)
{
$request_type = $request->headers->get('X-Requested-With');

if($request_type != 'XMLHttpRequest') {
return $this->render('HvHDashboardBundle:Dashboard:dashboard.html.twig' );
}

//get any query strings
$query_strings = $request->query->all();
$definition = $this->get("service.handler")->definition_handler(__CLASS__, __FUNCTION__);
//once data has been prepared
return $this->get('fos_rest.view_handler')->handle($view);

}
}

最佳答案

我认为 Controller 没有获得容器的原因是因为您试图实例化它并直接与其交互,而不是使用客户端模拟请求(请参阅 Symfony2 书中的 Testing section 中的功能测试部分)。

您需要类似这样的东西(不确定路线是否正确):

public function testGetClientsAction()
{
$client = static::createClient();

$client->request(
'GET', '/clients/123456',
array(), /* request params */
array(), /* files */
array('X-Requested-With' => "XMLHttpRequest"),
);

$this->assertEquals(200, $client->getResponse()->getStatusCode());
}

另请注意,request() 方法返回一个爬虫实例,该实例提供辅助方法来验证响应的内容(如果需要)。

关于Symfony 单元测试和容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com