我的很多测试都有很多相同的setUp()
/tearDown()
东西。将相同的代码复制并粘贴到我的每一个单元测试中似乎很愚蠢。我想我想创建一个新的测试类来扩展WebTestCase
我的其他测试可以扩展。
我的问题是我真的不知道怎么做。首先,在哪里放置这个新类最合适?我尝试在我的Tests
文件夹中制作一个,但是我的测试都没有真正找到该类。也许我只是不了解名称空间。
WebTestCase
有没有人以我所说的方式扩展过?如果是这样,你是怎么做到的?
我的很多测试都有很多相同的setUp()
/tearDown()
东西。将相同的代码复制并粘贴到我的每一个单元测试中似乎很愚蠢。我想我想创建一个新的测试类来扩展WebTestCase
我的其他测试可以扩展。
我的问题是我真的不知道怎么做。首先,在哪里放置这个新类最合适?我尝试在我的Tests
文件夹中制作一个,但是我的测试都没有真正找到该类。也许我只是不了解名称空间。
WebTestCase
有没有人以我所说的方式扩展过?如果是这样,你是怎么做到的?
我没有这样做,但我可能会这样做
src/Your/Bundle/Test/WebTestCase.php
<?php
namespace Your\Bundle\Test
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase as WTC;
class WebTestCase extends WTC
{
// Your implementation of WebTestCase
}
在我的测试中,我通常按照 Peter 建议的方式扩展 WebTestCase。此外,我使用 require_once 使 AppKernel 在我的 WebTestCase 中可用:
<?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()
{
...
您不需要扩展 WebTestCase 以包含 AppKernel。您可以使用以下方法
$client = static::createClient();
self::$application = new Application($client->getKernel());
这个问题真的很老,但它在谷歌上的排名很高,所以我想我会添加我的解决方案。
我扩展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.
}
Note: I'm using the Symfony 3
directory structure, hence why my tests are in tests/
and not src/AppBundle/Tests/
.
I hope this helps someone...