gpt4 book ai didi

unit-testing - Symfony2 + 功能测试 "DataFixtures load how set the proper order"

转载 作者:行者123 更新时间:2023-11-28 20:43:40 25 4
gpt4 key购买 nike

我正在学习测试我的 Symfony2 代码,但我正在尝试构建测试,所以我正在使用 DataFixtures 加载数据,顺便说一句,我认为这也测试了我的实体。我将使用一个测试作为示例:CreateCompanyControllerTest.php,这是我在每个测试中运行的基本代码:

private $em;

protected static $application;

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

self::runCommand('doctrine:schema:update --force');

$loader = new Loader();
$loader->addFixture(new LoadCompanyData());

$purger = new ORMPurger();
$executor = new ORMExecutor($this->em, $purger);
$executor->execute($loader->getFixtures());
}

protected static function runCommand($command) {
$command = sprintf('%s --quiet', $command);

return self::getApplication()->run(new StringInput($command));
}

protected static function getApplication() {
if (null === self::$application) {
$client = static::createClient();

self::$application = new Application($client->getKernel());
self::$application->setAutoExit(false);
}

return self::$application;
}

我不知道是否一直运行命令 doctrine:schema:update --force 是正确的,因为它会彻底清理我的数据库,这是我的第一个疑问。现在关于 LoadCompanyData.php 中的相同问题,我有一些实体依赖项(请参见下面的代码:

 $mediaType = $manager->getRepository('MediaBundle:NMediaType')->find(1);
$mediaStatus = $manager->getRepository('MediaBundle:NMediaStatus')->find(1);

但是由于我运行了命令 doctrine:schema:update --force 我的数据库被清理了,然后测试失败并显示了这条消息:

1) Company\RegisterCompanyBundle\Tests\Controller\CreateCompanyControllerTest::testcreateCompanyAction Argument 1 passed to Wuelto\Common\MediaBundle\Entity\Media::setType() must be an instance of Common\MediaBundle\Entity\NMediaType, null given, called in /var/www/html/kraken/src/Company/RegisterCompanyBundle/DataFixtures/ORM/LoadCompanyData.php on line 46 and defined

这是对的,因为那张 table 是空的。然后知道这一点:

  1. 有什么办法可以避免这种情况吗?
  2. 我是否应该为任何依赖实体创建一个夹具,然后在我需要的地方调用?在这种情况下,任何示例都可以,因为我不知道该怎么做。
  3. 我知道 Data Fixtures 中的 getOrder() 设置了加载 fixtures 的顺序,但是我该如何使用它呢?我的意思是,例如在为公司加载数据之前,我应该首先添加依赖实体的数据,对此有什么建议吗?

最佳答案

始终清理测试数据库是一种很好的做法,您的测试应该是自包含的,而不依赖于先前测试在数据库中遗留的任何内容。

话虽这么说,是的,您还应该设置固定装置或辅助函数,以在测试数据库中插入您需要的任何必要数据。

您可以为每个测试文件执行一次此设置。数据库测试很昂贵,也很耗时,所以如果您可以模拟调用数据库,那么您应该这样做,但这完全取决于您要测试的内容。

关于unit-testing - Symfony2 + 功能测试 "DataFixtures load how set the proper order",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22594672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com