【问题标题】:Access Symfony 2 container via Unit test?通过单元测试访问 Symfony 2 容器?
【发布时间】:2012-02-16 20:49:27
【问题描述】:

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

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

【问题讨论】:

标签: php unit-testing symfony


【解决方案1】:

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 的回答。并感谢您对注入容器的评论。干杯。
【解决方案2】:

你可以在你的设置函数中使用这个

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

【讨论】:

  • 这条评论应该被选中。谢谢楼主!
【解决方案3】:

2018 年更新:自 Symfony 3.4/4.0 以来,服务测试出现问题。

这叫“测试私服”,可能的解决方案是described here


对于各种不同的配置,您还可以使用 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);
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多