5

我的很多测试都有很多相同的setUp()/tearDown()东西。将相同的代码复制并粘贴到我的每一个单元测试中似乎很愚蠢。我想我想创建一个新的测试类来扩展WebTestCase我的其他测试可以扩展。

我的问题是我真的不知道怎么做。首先,在哪里放置这个新类最合适?我尝试在我的Tests文件夹中制作一个,但是我的测试都没有真正找到该类。也许我只是不了解名称空间。

WebTestCase有没有人以我所说的方式扩展过?如果是这样,你是怎么做到的?

4

4 回答 4

4

我没有这样做,但我可能会这样做

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
}
于 2012-06-07T19:47:08.930 回答
2

在我的测试中,我通常按照 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()
    {
...
于 2012-06-08T17:46:43.760 回答
2

您不需要扩展 WebTestCase 以包含 AppKernel。您可以使用以下方法

    $client = static::createClient();
    self::$application = new Application($client->getKernel());
于 2013-03-15T15:14:43.550 回答
0

这个问题真的很老,但它在谷歌上的排名很高,所以我想我会添加我的解决方案。

我扩展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...

于 2016-04-20T06:18:53.990 回答