简体   繁体   中英

How to get doctrine fixture references by type of fixture in test in symfony WebTestCase?

I am using doctrine fixtures to load test data in my symfony application.

 $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'
]);

In my test case, I want to test get paginated entities.

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());

}

I want to compare page from my fixtures and from api response. The problem is below line returns all fixture references. The entity I want to test is of type Entity6. Entity6 has dependency on all other types so I have to load all of them.

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

How do I get refernces of type Entity6 only ? I digged into

Doctrine\\Common\\DataFixtures\\ReferenceRepository::getReferences code

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

There is no option to get references of particular type. I tried looping on all references to check the class type using get_class

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

But references are proxy doctrine entitites so I am getting class type

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

How do I get references of entity type from doctrine fixtures ? Prefixing Proxies__CG__ might not be best way to do this ? What is the most reliable way ?

Don't use get_class , use instanceof :

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

Doctrine proxies inherit the entity class, thus fulfilling instanceof .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM