使用夹具加载后删除夹具

时间:2014-04-03 16:31:03

标签: 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());
}

由于记录是在设置中创建的,因此它们保留在测试失败的DB中。有什么建议吗?你是怎么解决的?

1 个答案:

答案 0 :(得分:3)

没有简单的方法可以做你要求的事情。通常做的是在执行测试之前和之后截断数据库,这样你就拥有了一个真正干净和孤立的环境。

引用这篇好文章(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