我的很多测试都有很多相同的setUp()
/ tearDown()
内容。将相同的代码复制并粘贴到我的每个单元测试中似乎都很愚蠢。我想我想创建一个扩展WebTestCase
的新测试类,我的其他测试可以扩展。
我的问题是我真的不知道怎么做。首先,这个新课程最合适的地方在哪里?我尝试在我的Tests
文件夹中创建一个,但是我的测试中没有一个能够真正找到该类。也许我只是不理解命名空间。
有没有人在我谈论的方式之前延长WebTestCase
?如果是这样,你是怎么做到的?
答案 0 :(得分:4)
我没有这样做,但我可能只是这样做
<强>的src /你/捆绑/测试/ WebTestCase.php 强>
<?php
namespace Your\Bundle\Test
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as WTC;
class WebTestCase extends WTC
{
// Your implementation of WebTestCase
}
答案 1 :(得分:2)
在我的测试中,我通常以彼得提出的方式扩展WebTestCase。另外,我使用require_once使我的WebTestCase中的AppKernel可用:
<?php
namespace My\Bundle\Tests;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as BaseWebTestCase;
require_once(__DIR__ . "/../../../../app/AppKernel.php");
class WebTestCase extends BaseWebTestCase
{
protected $_application;
protected $_container;
public function setUp()
{
$kernel = new \AppKernel("test", true);
$kernel->boot();
$this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
$this->_application->setAutoExit(false);
...
我的测试看起来像这样:
<?php
namespace My\Bundle\Tests\Controller;
use My\Bundle\Tests\WebTestCase;
class DefaultControllerTest extends WebTestCase
{
public function testIndex()
{
...
答案 2 :(得分:2)
您无需扩展WebTestCase以包含AppKernel。您可以使用以下方法
$client = static::createClient();
self::$application = new Application($client->getKernel());
答案 3 :(得分:0)
这个问题真的很陈旧,但在Google上排名很高,所以我想我会添加我的解决方案。
我使用默认的WebTestCase
方法和setUp
方法扩展了logIn
,因此我可以更轻松地运行经过身份验证的测试。
似乎您无法将标准类添加到tests
目录,因为单元测试将找不到它们。我不知道为什么。我的解决方案是添加目录src/_TestHelpers
并将我的帮助程序类放在那里。
所以我有:
# src/_TestHelpers/ExtendedWTC.php
namespace _TestHelpers;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class ExtendedWTC extends WebTestCase
{
# Do your cool extending here
}
和
# tests/AppBundle/Controller/DefaultControllerTest.php
namespace Tests\AppBundle;
use _TestHelpers\ExtendedWTC
class DefaultControllerTest extends ExtendedWTC
{
# Your tests here, using your cool extensions.
}
注意:我正在使用Symfony 3
目录结构,因此我的测试位于tests/
而不是src/AppBundle/Tests/
。
我希望这有助于某人...