繁体   English   中英

通过单元测试访问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-tools

它为您设置容器并准备使用:

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM