testing - Symfony 4.1 OneToMany 在测试中返回空
问题描述
为什么在我的测试中没有工作关系?例如,一个 Product 有两个 ProductVariant,但 $product->getVariants()->count() 返回 0,而 count($variants) 返回 2。
<?php
namespace App\Tests\Service\Marketplace\Banggood;
use App\Test\TestCase;
use Nelmio\Alice\Loader\NativeLoader;
class ImportOrderTest extends TestCase
{
public function test_transform()
{
$this->loadFixtures();
$product = $this->getEntityManager()->getRepository('App:Product')->findOneBy(['foreignId' => 93255]);
$variants = $this->getEntityManager()->getRepository('App:ProductVariant')->findBy(['product' => $product]);
dd($product->getVariants()->count(), count($variants));
}
protected function getEntityManager()
{
return $this->getService('doctrine.orm.entity_manager');
}
protected static function getService($id)
{
return self::$kernel->getContainer()->get($id);
}
protected function loadFixtures()
{
$loader = new NativeLoader();
$objectSet = $loader->loadFile(__DIR__."/../DataFixtures/test/fixtures.yaml");
foreach ($objectSet->getObjects() as $entity)
{
$this->getEntityManager()->persist($entity);
}
$this->getEntityManager()->flush();
}
我花了大约 4 个小时,但没有找到错误在哪里。
固定装置.yaml
App\Entity\Product:
product:
name: 'Product # 1'
foreignId: <numberBetween(1,99999)>
bodyHtml: <text(300)>
description: '<paragraph(1)>'
tags: ''
option1: "Size"
option2: "Color"
App\Entity\ProductVariant:
pv{1..2}:
product: '@product'
name: 'Variant <current()>'
grams: <numberBetween(100, 1000)>
sku: <ean8()>
option1 (unique): <numberBetween(1, 200)>
option2: "<randomElement(['red', 'yellow', 'black', 'green', 'white'])>"
我的装置工作正常,在数据库中我看到 products 表中有一行,product_variants 表中有两行。
来自 App\Entity\Product 类的片段
/**
* @ORM\OneToMany(targetEntity="App\Entity\ProductVariant", mappedBy="product", orphanRemoval=true, cascade={"persist"})
*/
private $variants;
/**
* @return Collection|ProductVariant[]
*/
public function getVariants(): Collection
{
return $this->variants;
}
解决方案
我发现了这个错误,它在我的固定装置中。下面代码的正确变体。
App\Entity\Product:
product:
name: 'Product # 1'
foreignId: <numberBetween(1,99999)>
bodyHtml: <text(300)>
description: '<paragraph(1)>'
tags: ''
option1: "Size"
option2: "Color"
variants: '@pv{1..2}'
App\Entity\ProductVariant:
pv{1..2}:
name: 'Variant <current()>'
grams: <numberBetween(100, 1000)>
sku: <ean8()>
option1 (unique): <numberBetween(1, 200)>
option2: "<randomElement(['red', 'yellow', 'black', 'green', 'white'])>"
推荐阅读
- instagram - 如何从 instaloader 下载主题标签的热门帖子
- c# - 有没有办法从 gridview 列计算增值税(增值税 = 15%)?
- jmeter - 在 JMeter 中参数化源文件夹目录或文件路径
- python - 如果在 Python 中加载此文件的时间超过 X 秒,如何中断加载命令?
- c++ - Autotools:如何覆盖中间构建产品目录?
- sql-server - 传递动态视图名称和条件
- flutter - 针对特定用例在不同页面上保持相同状态
- javascript - 如何仅将特定键值对从一个对象添加到另一个对象?
- react-native - 为什么我的代码会导致我的组件出现一瞬间?
- sql - SQL Server 用最后一个值替换 NULL