我正在尝试使用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
...
*/
}
我试过了:
$request = \Symfony\Component\HttpFoundation\Request::create(
$uri, $method, $parameters, $cookies, $files, $server, $content);
$my_controller = new MyController();
$my_controller->submitAction($request, $id);
从我的单元测试来看,但是似乎还有很多其他设置我不知道Symfony在后台执行。每当我找到一个丢失的对象并将其初始化时,就会有另一个在某个时刻失败。
我也尝试过逐步通过PhpStorm进行测试,但是PhpUnit的某些输出会导致Symfony在它接近我要测试的代码之前就死掉,因为它无法在$_SESSION
发生任何输出后启动。我不认为这是从命令行发生的,但是我还不够接近。
如何在单元测试中简单且可扩展地运行此代码?
一点背景:
我继承了这段代码。我知道它很脏而且有异味,因为它正在控制器中执行模型逻辑。我知道我要的不是“纯粹的”单元测试,因为它实际上涉及整个应用程序。
但是我需要能够自动运行这一“小”(200多行)的代码。该代码应在不超过几秒钟的时间内运行。我不知道要多久,因为我从未能够独立运行它。
当前,通过网站运行此代码的设置时间非常长,而且很复杂。该代码不会生成网页,基本上是生成文件的API调用。在进行代码更改时,我需要能够在短时间内生成尽可能多的这些测试文件。
代码就是它。能够对其进行更改是我的工作,目前我什至每次都没有大量开销就无法运行它。在不知道它在做什么的情况下对其进行更改是不负责任的。
我发现将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);
此代码之后,您可以在控制器上测试任何公共方法。当然,如果您要测试生产代码(必须这样做;由于代码库编写得很糟糕,我的开发代码的工作方式将完全不同),请注意,您可能正在接触数据库,进行Web调用等。
但是,好处是您可以开始对控制器进行代码覆盖,以了解它们为何无法正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句