【问题标题】:How to use existing data from the database in Codeception FactoryMuffin?如何在 Codeception FactoryMuffin 中使用数据库中的现有数据?
【发布时间】:2026-02-12 22:50:01
【问题描述】:

我正在尝试在验收测试中设置简单的测试数据:

  public function shouldUseAFakeAccountHolder(AcceptanceTester $I) {
    $I->have(AccountHolder::class);
    // ...
  }

我复制了the example code from the Codeception documentation 并用我的实体名称对其进行了修改(以及修复了错误)。

<?php
public function _beforeSuite()
{
     $factory = $this->getModule('DataFactory');
     // let us get EntityManager from Doctrine
     $em = $this->getModule('Doctrine2')->_getEntityManager();

     $factory->_define(AccountHolder::class, [
         'firstName' => Faker::firstName(),

         // Comment out one of the below 'accountRole' lines before running:

         // get existing data from the database
         'accountRole' => $em->getRepository(AccountRole::class)->find(1),

         // create a new row in the database
         'accountRole' => 'entity|' . AccountRole::class,
     ]);
}

使用现有数据'accountRole' =&gt; $em-&gt;getRepository(AccountRole::class)-&gt;find(1)的关系总是失败:

 [Doctrine\ORM\ORMInvalidArgumentException] A new entity was found through the relationship 'HMRX\CoreBundle\Entity\AccountHolder#accountRole' that was not configured to cascade persist operations for entity: HMRX\CoreBundle\Entity\AccountRole@0000000062481e3f000000009cd58cbd. To solve this issue: Either explicitly call EntityManager#persist() on this unknown entity or configure cascade persist  this association in the mapping for example @ManyToOne(..,cascade={"persist"}). If you cannot find out which entity causes the problem implement 'HMRX\CoreBundle\Entity\AccountRole#__toString()' to get a clue.

如果我告诉它在相关表'accountRole' =&gt; 'entity|' . AccountRole::class 中创建一个新条目,它会起作用,但是当它应该使用现有行时,它会向表中添加行。所有的角色类型都是预先知道的,一个新的随机角色类型没有意义,因为在它的代码中没有任何东西可以匹配。创建一个重复的角色是可行的,但是再次为每个用户设置一个单独的角色类型是很有意义的,因为角色应该由用户共享。

我之前在不使用Faker/FactoryMuffin 的单元测试中遇到过这个错误,而不是验收测试,这与使用EntityManager 的不同实例访问关系的每个实体有关。一旦我使用相同的实例获得了两个部分,它就起作用了。不过,我看不到如何在此处覆盖本机行为。

【问题讨论】:

    标签: codeception faker factorymuffin


    【解决方案1】:

    它通过对现有关系使用回调来工作(至少在 Codeception 4.x 中):

    <?php
    public function _beforeSuite()
    {
         $factory = $this->getModule('DataFactory');
         $em = $this->getModule('Doctrine2')->_getEntityManager();
    
         $factory->_define(AccountHolder::class, [
             'firstName' => Faker::firstName(),
    
             'accountRole' => function($entity) use ($em) {
                 $em->getReference(AccountRole::class)->find(1);
             },
         ]);
    }
    

    我在这里找到了它:https://github.com/Codeception/Codeception/issues/5134#issuecomment-417453633

    【讨论】: