我正在使用DataFixtures用单元测试的数据填充测试数据库。
对于不使用其他实体的实体,我可以使用setId设置主键。对于其他实体使用的实体,我可以设置它,但是将其忽略。
例如我正在这样设置用户:
/** @var Gender $genderW */
$genderM = $this->getReference(GenderFixtures::TEST_GENDER_W);
$date = new DateTime('now');
/** @var User $user */
$user = new User();
$user
->setId(9)
->setFirstName('Hermione')
->setLastName('Granger')
->setEmail('test9@example.com')
->setGender($genderM)
->setPassword('odsf3_!45sr-f')
->setCreated($date);
$manager->persist($user);
$manager->flush();
$this->addReference(self::TEST_USER_REFERENCE_9, $user);
如您所见,我为Hermione设置了ID,但是如果我在测试中执行var_dump,则会看到我所运行的每个测试的用户ID都会增加我的用户数。 (9,18,27 ....)
结果是,在我的测试中,我必须通过唯一的电子邮件地址来获取用户,这是可能的,但是很烦人:
$userRepo = $this->em->getRepository(User::class);
$this->user = $userRepo->findOneBy(['email' => 'test9@example.com']);
var_dump($this->user->getId());
是否可以更改此设置,以便按ID吸引我的用户?
config:
"require": {
"php": "7.2.*",
"ext-ctype": "*",
"ext-iconv": "*",
"cache/predis-adapter": "^1.0",
"doctrine/doctrine-bundle": "^1.6.10",
"doctrine/doctrine-migrations-bundle": "^1.3",
"doctrine/orm": "^2.5.11",
"eightpoints/guzzle-bundle": "~7.3.1",
"friendsofsymfony/rest-bundle": "^2.3",
"guzzlehttp/guzzle": "^6.3",
"jms/serializer-bundle": "^2.4",
"predis/predis": "^1.1",
"sensio/framework-extra-bundle": "^5.2",
"snc/redis-bundle": "3.x-dev",
"symfony/apache-pack": "^1.0",
"symfony/console": "^4.1",
"symfony/flex": "^1.0",
"symfony/framework-bundle": "^4.1",
"symfony/lts": "^4@dev",
"symfony/monolog-bundle": "^3.1",
"symfony/orm-pack": "^1.0",
"symfony/polyfill-apcu": "^1.5",
"symfony/security-bundle": "^4.0",
"symfony/swiftmailer-bundle": "^3.2",
"symfony/twig-bundle": "^4.1",
"symfony/validator": "^4.1",
"symfony/yaml": "^4.1"
},
"require-dev": {
"diablomedia/phpunit-pretty-printer": "2.0.*",
"doctrine/doctrine-fixtures-bundle": "^3.0",
"friendsofphp/php-cs-fixer": "*",
"phpmd/phpmd": "^2.6",
"sensiolabs/security-checker": "^4.1",
"squizlabs/php_codesniffer": "*",
"symfony/dotenv": "^4.1",
"symfony/maker-bundle": "^1.5",
"symfony/phpunit-bridge": "^4.1",
"symfony/var-dumper": "^4.1"
},
答案 0 :(得分:0)
正确的方法是在每个类中/为您的Testsuite创建一个setUp
和tearDown
方法。
使用这些方法,您可以在每次运行数据库时在数据库中创建/截断测试数据。
根据Databasetesting的Phpunit文档,设置将在运行测试之前清除
PHPUnit将对您指定的所有表执行TRUNCATE,以将其状态重置为空。
仅进行截断,不重置自动增量值。
要清理数据库密钥,应使用tearDown
进行测试以重置密钥
ALTER TABLE表名AUTO_INCREMENT = 1
这将在每次测试后重置自动增量值。
要仅通过symfony实现此目的,您可以创建一个命令来执行以下操作:
./app/console doctrine:fixtures:load --purge-with-truncate
found this command on SO 您将有1条命令仅使用symfony运行测试。