通过单元测试访问Symfony 2容器


Access Symfony 2 container via Unit test?

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

测试类扩展了'PHPUnit_Framework_TestCase,因此没有容器。

支持现已内置到Symfony中。看见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.

请注意,在单元测试中使用容器会产生气味。一般来说,这意味着你的类依赖于整个容器(整个世界),这是不好的。你应该限制你的依赖关系并嘲笑它们。

您可以在设置函数中使用它

protected $client;
protected $em;
/**
 * PHP UNIT SETUP FOR MEMORY USAGE
 * @SuppressWarnings(PHPMD.UnusedLocalVariable) crawler set instance for test.
 */
public function setUp()
{
    $this->client = static::createClient(array(
            'environment' => 'test',
    ),
        array(
            'HTTP_HOST' => 'host.tst',
            'HTTP_USER_AGENT' => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0',
    ));
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()
                               ->get('doctrine')
                               ->getManager();
    $crawler = $this->client->followRedirects();
}

别忘了设置你的拆卸功能

    protected function tearDown()
{
    $this->em->close();
    unset($this->client, $this->em,);
}

更新2018:由于Symfony 3.4/4.0,服务测试存在问题

它被称为"测试私人服务",这里描述了可能的解决方案


对于各种不同的配置,您还可以使用lastzero/test工具包

它为您设置了一个容器,并准备使用:

use TestTools'TestCase'UnitTestCase;
class FooTest extends UnitTestCase
{
    protected $foo;
    public function setUp()
    {
        $this->foo = $this->get('foo');
    }
    public function testBar()
    {
        $result = $this->foo->bar('Pi', 2);
        $this->assertEquals(3.14, $result);
    }
}