我正在尝试在验收测试中设置简单的测试数据:
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,
]);
}使用现有data 'accountRole' => $em->getRepository(AccountRole::class)->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' => 'entity|' . AccountRole::class中创建一个新条目,它就可以工作,但是它会在应该使用现有行的时候向表中添加行。所有的角色类型都是预先知道的,一个新的随机角色类型没有任何意义,因为在代码中没有任何东西可以与之匹配。创建一个重复的角色是可行的,但是对于每个用户都有一个单独的角色类型是非常有意义的,因为角色应该由用户共享。
我以前在单元测试中遇到过这个错误,而不是在不使用Faker / FactoryMuffin的情况下进行验收测试,它与使用不同的EntityManager实例访问关系的每个实体有关。一旦我使用相同的实例获取了两个部分,它就工作了。不过,我不知道如何在这里覆盖本机行为。
发布于 2020-09-08 20:59:28
它通过对现有关系使用回调来工作(至少在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
https://stackoverflow.com/questions/59166523
复制相似问题