如何对Symfony控制器进行单元测试

CJ *_*nis 5 php phpunit unit-testing symfony codeception

我正在尝试使用Codeception在测试工具中使用Symfony控制器。每种方法的开始如下:

public function saveAction(Request $request, $id)
{
    // Entity management
    /** @var EntityManager $em */
    $em = $this->getDoctrine()->getManager();

    /* Actual code here
    ...
    */
}

public function submitAction(Request $request, $id)
{
    // Entity management
    /** @var EntityManager $em */
    $em = $this->getDoctrine()->getManager();

    /* 200+ lines of procedural code here
    ...
    */
}
Run Code Online (Sandbox Code Playgroud)

我试过了:

$request = \Symfony\Component\HttpFoundation\Request::create(
    $uri, $method, $parameters, $cookies, $files, $server, $content);

$my_controller = new MyController();
$my_controller->submitAction($request, $id);
Run Code Online (Sandbox Code Playgroud)

从我的单元测试来看,但是似乎还有很多其他设置我不知道Symfony在后台执行。每当我找到一个丢失的对象并将其初始化时,就会有另一个在某个时刻失败。

我也尝试过逐步从PhpStorm进行测试,但是PhpUnit的某些输出会导致Symfony在它接近我要测试的代码之前就死掉,因为它无法在$_SESSION发生任何输出后启动。我不认为这是从命令行发生的,但是我还不够接近。

如何在单元测试中简单且可扩展地运行此代码?


一点背景:

我继承了这段代码。我知道它很脏而且有异味,因为它正在控制器中执行模型逻辑。我知道我要的不是“纯粹的”单元测试,因为它实际上涉及整个应用程序。

但是我需要能够自动运行这一小段(200行以上)的代码。该代码应在不超过几秒钟的时间内运行。我不知道要多久,因为我从未能够独立运行它。

当前,通过网站运行此代码的设置时间非常长,而且很复杂。该代码不会生成网页,基本上是生成文件的API调用。在进行代码更改时,我需要能够在短时间内生成尽可能多的这些测试文件。

代码就是它。能够对其进行更改是我的工作,现在我什至每次都没有大量开销就无法运行它。在不知道它在做什么的情况下进行更改是不负责任的。

CJ *_*nis -1

我发现只需几行简短的代码就可以将 Symfony 纳入测试工具:

// Load the autoloader class so that the controller can find everything it needs
//$loader = require 'app/vendor/autoload.php';
require 'app/vendor/autoload.php';

// Create a new Symfony kernel instance
$kernel = new \AppKernel('prod', false);
//$kernel = new \AppKernel('dev', true);
// Boot the kernel
$kernel->boot();
// Get the kernel container
$container = $kernel->getContainer();
// Services can be retrieved like so if you need to
//$service = $container->get('name.of.registered.service');

// Create a new instance of your controller
$controller = new \What\You\Call\Your\Bundle\Controller\FooBarController();
// You MUST set the container for it to work properly
$controller->setContainer($container);
Run Code Online (Sandbox Code Playgroud)

在此代码之后,您可以在控制器上测试任何公共方法。当然,如果您正在测试生产代码(我必须这样做;我的开发代码的工作方式完全不同,因为代码库编写得非常糟糕),请注意您可能正在接触数据库、进行网络调用等。

然而,好处是您可以开始对控制器进行代码覆盖,以了解它们无法正常工作的原因。