首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Codeception中使用数据库中的现有数据?

如何在Codeception中使用数据库中的现有数据?
EN

Stack Overflow用户
提问于 2019-12-04 06:45:01
回答 1查看 220关注 0票数 0

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

代码语言:javascript
复制
  public function shouldUseAFakeAccountHolder(AcceptanceTester $I) {
    $I->have(AccountHolder::class);
    // ...
  }

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

代码语言:javascript
复制
<?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,
     ]);
}

使用现有data 'accountRole' => $em->getRepository(AccountRole::class)->find(1)的关系始终失败:

代码语言:javascript
复制
 [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' => 'entity|' . AccountRole::class中创建一个新条目,它就可以工作,但是它会在应该使用现有行的时候向表中添加行。所有的角色类型都是预先知道的,一个新的随机角色类型没有任何意义,因为在代码中没有任何东西可以与之匹配。创建一个重复的角色是可行的,但是对于每个用户都有一个单独的角色类型是非常有意义的,因为角色应该由用户共享。

我以前在单元测试中遇到过这个错误,而不是在不使用Faker / FactoryMuffin的情况下进行验收测试,它与使用不同的EntityManager实例访问关系的每个实体有关。一旦我使用相同的实例获取了两个部分,它就工作了。不过,我不知道如何在这里覆盖本机行为。

EN

回答 1

Stack Overflow用户

发布于 2020-09-08 20:59:28

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

代码语言:javascript
复制
<?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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59166523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档