【问题标题】:Symfony problem with fixtures when running phpunit with sqlite使用 sqlite 运行 phpunit 时,夹具的 Symfony 问题
【发布时间】:2019-04-06 22:01:43
【问题描述】:

我正在尝试配置 symfony 以使用 sqlite 进行测试。

composer.json (require-dev)

"doctrine/doctrine-fixtures-bundle": "^3.1",
"liip/functional-test-bundle": "~2.0@alpha",

config/packages/test/doctrine.yaml:

doctrine:
  dbal:
    driver: 'pdo_sqlite'
    url: 'sqlite:///%kernel.project_dir%/var/test.db3'

然后我做了一个这样的测试

class SimplestTest extends WebTestCase
{

private $fixtures;

public function setUp()
{
    $this->fixtures = $this->loadFixtures([
        MyFixtures::class
        ])->getReferenceRepository();
}

public function testToSeeIfItWorks()
{
    $this->assertTrue(true);
}
}

MyFixtures 类扩展 AbstractFixture 并加载一些简单的对象:

class MyFixtures extends AbstractFixture
{
public function load(ObjectManager $manager)
{

    $user1 = new User();
    $user1->setRoles(['ROLE_USER']);

    $manager->persist($user1);
    $manager->flush();

    $myFeed = new Feed();
    $myFeed->setName('Feed 1');
    $myFeed->setUrl('http://someurl');
    $myFeed->setUser($user1);

    $manager->persist($myFeed);
    $manager->flush();
}
}

当我运行测试时,我得到:

InvalidArgumentException: "App\Tests\DataFixtures\ORM\MyFixtures" is not a registered fixture

不知道为什么。有什么帮助吗?

谢谢

【问题讨论】:

  • 你能粘贴 MyFixtures 的代码吗?
  • @Emma 已经尝试过同样的事情
  • @MichałTomczuk 我用夹具代码更新了问题。
  • 检查 AbstractTest 类here 注册了fixture。
  • @user3174311 你的整个代码看起来应该可以工作。我要改变一件事——你在MyFixture 中刷新两次,删除第一个$manager->flush()。也许,无论出于什么黑暗教义的原因,它都会产生错误。

标签: php symfony phpunit


【解决方案1】:

我想我知道问题出在哪里。如果涉及到夹具应该扩展的类,库的文档中似乎存在一个错误。在the documentation 状态下使用Doctrine\Common\DataFixtures\AbstractFixture,但它使fixture 不会自动加载。

正如您在 DoctrineFixturesBundle documentation 中所读到的,该包将通过自动装配添加一个 doctrine.fixture.orm 标记到任何实现 ORMFixtureInterface 的类,例如 Doctrine\Bundle\FixturesBundle\Fixture。从实现接口的类中加载夹具由FixturesCompilerPass 完成。

如果您将夹具的基类更改为Doctrine\Bundle\FixturesBundle\Fixture,它应该可以工作。

更新:

除此之外,fixture 类必须位于 App\DataFixtures 命名空间中。

这是因为该命名空间被配置为自动装配和自动配置。如果您想将您的夹具文件保留在App\Tests\DataFixtures\ 下,请在config/services.yaml 文件中添加正确的配置:

services:
    App\Tests\DataFixtures\:
        resource: '../tests/DataFixtures'

【讨论】:

  • 不幸的是,这不起作用。顺便说一句,我有另一个固定装置类,它使用我用于开发的数据扩展固定装置,并且当我运行教义:固定装置:加载时它可以工作。但是这个是由phpunit的测试内核使用的,所以我认为这是一个与sqlite相关的配置问题。此外,如果我将 config/packages/test/doctrine.yaml 更改为使用 mysql,它也可以工作。
  • 好的,尝试将灯具从src/Tests/DataFixtures/ORM移动到src/DataFixtures。当我将我的灯具从src/DataFixtures 移动到与您的结构类似的目录时,我收到了关于灯具未注册的错误 - 也许这是灯具自动加载的另一个要求?一定要让它扩展Fixture,就像在答案中一样。
  • 太棒了!这实际上可以解决问题。现在我要看看其他一切是否按预期工作,比如为我的功能测试创建客户端,但错误消失了。我认为您应该修改答案以包含这一点,以防其他人将来需要它。非常感谢。
猜你喜欢
  • 2019-11-22
  • 1970-01-01
  • 2017-02-14
  • 1970-01-01
  • 2023-03-30
  • 2017-09-23
  • 1970-01-01
  • 1970-01-01
  • 2013-05-29
相关资源
最近更新 更多