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

43

如何在单元测试中访问Symfony 2容器?我的库需要它,所以这很重要。

测试类继承了\PHPUnit_Framework_TestCase,因此没有容器。


1
https://dev59.com/eWw05IYBdhLWcg3w0VKa#7016258 - JamesHalsall
3个回答

95

现在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

请注意,在单元测试中使用容器是不好的做法。通常意味着你的类依赖于整个容器(整个世界),这并不好。你应该限制你的依赖关系并对它们进行模拟。


感谢@Jakub的回答。也感谢您关于注入容器的评论。干杯。 - Anjana Silva

12
你可以在你的设置函数中使用这个。
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,);
}

1
这个注释应该被选中。谢谢先生! - D_R

1

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

https://www.tomasvotruba.cz/blog/2018/05/17/how-to-test-private-services-in-symfony/ - Tomas Votruba
你可以创建 services_test.yaml 文件,为你想访问的那些服务定义别名并将它们公开。 - Federico J. Álvarez Valero
1
这是浪费编程时间的最糟糕的方式,请参见https://www.tomasvotruba.cz/blog/2018/05/17/how-to-test-private-services-in-symfony/#down-the-smelly-rabbit-hole - Tomas Votruba

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接