unit-testing - 使用 Fixtures 加载后删除 fixtures

标签 unit-testing symfony testing functional-testing

我正在对我的代码进行一些测试,我得到了我的第一个“停止”,因为我不知道如何继续前进。在我加载灯具的 setUp() 函数中看到:

public function setUp() {
    static::$kernel = static::createKernel();
    static::$kernel->boot();
    $this->em = static::$kernel->getContainer()->get('doctrine')->getManager();
    $this->user = $this->createUser();

    $fix = new MetaDetailGroupFixtures();
    $fix->load($this->em);

    parent::setUp();
}

但后来我删除了创建的数据,因为我对坏情况进行了测试(当没有返回实体时):

public function testListMetaDetailGroupFailAction() {
    $client = static::createClient();
    $this->logIn($client, $this->user);

    $route = $client->getContainer()->get('router')->generate('meta-detail-group-list', array('parent_id' => 20000), false);
    $client->request("GET", $route);

    $decoded = json_decode($client->getResponse()->getContent(), true);

    $this->assertCount(0, $decoded['entities']);
    $this->assertArrayHasKey('success', $decoded);
    $this->assertJsonStringEqualsJsonString(json_encode(array("success" => false, "message" => "No existen grupos de metadetalles de productos creados")), $client->getResponse()->getContent());
    $this->assertSame(200, $client->getResponse()->getStatusCode());
    $this->assertSame('application/json', $client->getResponse()->headers->get('Content-Type'));
    $this->assertNotEmpty($client->getResponse()->getContent());
}

由于记录是在设置中创建的,并且它们保留在测试失败的数据库中。对此有何建议?你的是怎么解决的?

最佳答案

没有简单的方法可以完成您的要求。通常所做的是在执行测试之前和之后截断数据库,以便您拥有一个真正干净和隔离的环境。

引用这篇不错的文章 ( http://blog.sznapka.pl/fully-isolated-tests-in-symfony2/ :

public function setUp()
{
    $kernel = new \AppKernel("test", true);
    $kernel->boot();
    $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    $this->_application->setAutoExit(false);
    $this->runConsole("doctrine:schema:drop", array("--force" => true));
    $this->runConsole("doctrine:schema:create");
    $this->runConsole("doctrine:fixtures:load", array("--fixtures" => __DIR__ . "/../DataFixtures"));
}

如您所见,此解决方案使用 Doctrine 的 Symfony2 命令来实现隔离状态。有一个我喜欢使用的包,它正好解决了这个问题,让您可以很好地使用 FunctionalTest 基类和许多其他功能。检查一下:

https://github.com/liip/LiipFunctionalTestBundle

关于unit-testing - 使用 Fixtures 加载后删除 fixtures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843668/

相关文章:

java - JUnit 预期异常

php - Symfony 3 在 FormType 中注入(inject)容器

c# - SetValue 测试在我的 Period 类上成功但在我的 Name 类上失败

ios - 在真实设备上测试 PhoneGap 应用程序

ruby-on-rails - rails 4 : Why do fixtures make this test fail?

laravel - 在 Lumen 中进行单元测试时,数据库迁移和事务之间有什么区别?

php - 产品中的 Symfony2 转储 Assets 具有不同的代码

java - Selenium - 在父级中搜索项目

ruby - 如何测试一个元素是从列表中随机选择的?

caching - Symfony2 app.php 可以工作,但 app_dev.php 不行