我正在对我的代码进行一些测试,我得到了我的第一个“停止”,因为我不知道如何继续前进。在我加载灯具的 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 基类和许多其他功能。检查一下:
关于unit-testing - 使用 Fixtures 加载后删除 fixtures,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22843668/