通过单元测试访问 Symfony 2 容器? [英] Access Symfony 2 container via Unit test?

查看:20
本文介绍了通过单元测试访问 Symfony 2 容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在单元测试中访问 Symfony 2 容器?我的图书馆需要它,所以它必不可少.

How do I access the Symfony 2 container within a Unit test? My libraries need it so it's essential.

测试类扩展了 \PHPUnit_Framework_TestCase 所以没有容器.

The test classes extend \PHPUnit_Framework_TestCase so there is no container.

推荐答案

支持现已内置到 Symfony 中.见 http://symfony.com/doc/master/cookbook/testing/doctrine.html

Support is now built into Symfony. See http://symfony.com/doc/master/cookbook/testing/doctrine.html

您可以这样做:

namespace AppBundle\Tests;

use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;

class MyDatabaseTest extends KernelTestCase
{
    private $container;

    public function setUp()
    {
        self::bootKernel();

        $this->container = self::$kernel->getContainer();
    }
}

有关更现代和可重用的技术,请参阅https://gist.github.com/jakzal/a24467c2e57d835dcb65.

For a bit more modern and re-usable technique see https://gist.github.com/jakzal/a24467c2e57d835dcb65.

请注意,在单元测试中使用容器会有异味.通常,这意味着您的课程依赖于整个容器(整个世界),这并不好.您应该限制您的依赖项并模拟它们.

Note that using container in unit tests smells. Generally it means your classes depend on the whole container (whole world) and that is not good. You should rather limit your dependencies and mock them.

这篇关于通过单元测试访问 Symfony 2 容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆