首页 > 解决方案 > 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;
}

标签: testingphpunitsymfony4

解决方案


我发现了这个错误,它在我的固定装置中。下面代码的正确变体。

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'])>"

推荐阅读