Tow*_*wer 40 php unit-testing symfony
如何在单元测试中访问Symfony 2容器?我的图书馆需要它,所以它是必不可少的.
测试类扩展,\PHPUnit_Framework_TestCase
因此没有容器.
Jak*_*las 90
现在支持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();
}
}
Run Code Online (Sandbox Code Playgroud)
有关更现代和可重复使用的技术,请参阅https://gist.github.com/jakzal/a24467c2e57d835dcb65.
请注意,在单元测试中使用容器会闻到异味.一般来说,这意味着你的类依赖于整个容器(整个世界),这并不好.您应该限制依赖关系并模拟它们.
小智 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();
}
Run Code Online (Sandbox Code Playgroud)
不要忘记设置你的拆解功能
protected function tearDown()
{
$this->em->close();
unset($this->client, $this->em,);
}
Run Code Online (Sandbox Code Playgroud)