【问题标题】:How to get doctrine fixture references by type of fixture in test in symfony WebTestCase?如何在 symfony WebTestCase 的测试中按夹具类型获取教义夹具参考?
【发布时间】:2016-03-09 05:20:45
【问题描述】:

我正在使用学说夹具在我的 symfony 应用程序中加载测试数据。

 $this->fixtureLoader = $this->loadFixtures([
            "My\DemonBundle\DataFixtures\ORM\LoadEntity1Data",
            "My\DemonBundle\DataFixtures\ORM\LoadEntity2Data",
            "My\DemonBundle\DataFixtures\ORM\LoadEntity3Data",
            "My\DemonBundle\DataFixtures\ORM\LoadEntity4Data",
            "My\DemonBundle\DataFixtures\ORM\LoadEntity5Data",
            'My\DemonBundle\DataFixtures\ORM\LoadEntity6Data'
]);

在我的测试用例中,我想测试获取分页实体。

public function testGetPaginated()
{

    $entities6 = $this->fixtureLoader->getReferenceRepository()->getReferences();

    $expected = array_slice($entities6, 3, 3);

    $this->client = static::makeClient();
    $this->client->request('GET', '/api/v1/entities6', ["page" => 2, "limit" => 3, "order" => "id", "sort" => "asc"], array(), array(
        'CONTENT_TYPE' => 'application/json',
        'HTTP_ACCEPT' => 'application/json'
    ));


   $this->assertSame($expected, $this->client->getResponse()->getContent());

}

我想比较来自我的装置和来自 api 响应的页面。问题在于下面的行返回所有夹具引用。我要测试的实体是 Entity6 类型的。 Entity6 依赖于所有其他类型,因此我必须加载所有其他类型。

$entities = $this->fixtureLoader->getReferenceRepository()->getReferences();

如何仅获取 Entity6 类型的引用?我深入研究了

Doctrine\Common\DataFixtures\ReferenceRepository::getReferences 代码

/**
 * Get all stored references
 *
 * @return array
 */
public function getReferences()
{
    return $this->references;
}

没有选项可以获取特定类型的引用。我尝试循环所有引用以使用 get_class 检查类类型

    foreach ($references as $reference) {
        $class = get_class($obj);
        if ($class == "My\DemonBundle\Entity\ORM\Entity6") {
            $expected[] = $obj;
        }
    }

但引用是代理学说实体,所以我得到类类型

Proxies\__CG__\My\DemonBundle\Entity\ORM\Entity6

我如何从理论固定装置中获取实体类型的引用?前缀 Proxies__CG__ 可能不是最好的方法吗?什么方法最靠谱?

【问题讨论】:

    标签: php symfony doctrine-orm fixtures alice-fixtures


    【解决方案1】:

    不要使用get_class,使用instanceof

    foreach ($references as $reference) {
        if ($reference instanceof \My\DemonBundle\Entity\ORM\Entity6) {
            $expected[] = $obj;
        }
    }
    

    Doctrine 代理继承实体类,从而实现instanceof

    【讨论】:

      猜你喜欢
      • 2012-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 2022-12-09
      相关资源
      最近更新 更多